currently I have in one system implemented solution for my problem. But I think there exists better solution, but I have not found it yet. I hope someone could find couliton or hint in me some direciton.
I have system for spliting different kind of jobs. Each work is in PostgreSQL database in table "jobs", where one row is one job (can be done multiple times). Each job has an attribute how many times it can be done (how many users can work on it). So my table jobs works like this:
ID_JOB NAME DONE HAS_TO_BE_DONE
1 Puzzle Solving 2 3
2 Washing Dishes 1 3
When users comes and ask for job:
- User gets id of job when job meets condition
DONE < HAS_TO_BE_DONE
- For given job value DONE is incremented ( +1 )
It works, but when more users are working simultaneously I need to everytime LOCK (type: SERIALIZABLE) database (even for reading).
If I would not used database locking probled could occur: User #1 comes - he is in step 1, (he knows Id of job he got), in same time (a few miliseconds later) comes User #2 and will ask for job and will be in step 1 and will get same job as User #1 because #User 1 did not managed step 2 yet (and didn't incremente DONE). This is reason why I have to completely lock database.
Does anyone know how to improve this method? Currently it works, but in moment when 100 users are working simultaneously database locking is causing slowing application. Problems are these two steps when in first step I will find job for user and then in second step I increment value.
If anyone would come with better solution I would be happy. Thank you