I implemented a Web Service with Java Servlets.
I got the following setup:
There is a database which handles ‘job’-entries. Each job has a status like ‘executing’ or ‘in queue’ or ‘finished’. If a user starts a new job, there is made an entry in the database with a job and the status ‘in queue’.
The job should only be executed if less than five other jobs are already executed. If there are five others already executing the status needs to stay ‘in queue’ and a Cronjob will handle the execution of this job later.
Now I just wonder, that if there are less than five jobs executing at the moment, my Script will execute this job. But what if at the same time, between my script asking the database how many jobs are being executed and the script starting to execute the job, another request from another user creates a job and also gets ‘four executing jobs’ as a result from the database.
Then there would be a race condition and 6 jobs would be executed.
How can I prevent something like that?
Any advice? Thank you very very much!