Priority queue in Java, so each producer gets one turn at a time
If I have multiple users (not countable) who each queue work items, how can I implement a queue so that each user gets one turnover at a time?
For example, if I have ABC users and they have a queue like [AABCDAAB CA], I would like it to be processed in that order [ABCDABCAA]
This would be easy to implement, but what if more processing of the current queue items would work at work. So:
- Start from Queue: [AABCDAABCA]
- Queue processing: ABCD
- Now it's the turn: [AAABCA]
- Added additional work: [AAABCADEABC]
- Process queue ABCDE
etc.
I don't know in advance how many different possible users there will be, so can't just iterate over a predefined list of users and do the job (if any) for each. I don't care about each user work being processed until no user gets two units of work while other users are waiting for work.
source to share
So how I would solve this problem off my head would be to have a hashmap where different users (i.e. A, B, C, D, etc.) would be keys, and the value associated with each key would be the number of "turns" they left. Then you can just iterate over the map, check if the "user" has more "twists", if they do, handle it, if they don't, move on to the next "user".
edit: use an array protected by mutex locks, or some streaming ordered object to store each processed user. Also add users to the concurrenthashmap as keys, where the value associated with each key is the number of steps until they are done. Have one more variable that holds the current position in the list.
source to share