In java, what is an efficient solution to the following problem:
I have multiple threads (10-20 or so) generating jobs (“Job Creators”), and a single thread capable of performing them (“The worker”). Once a job creator has posted a job, it should wait for the job to finish, yielding no result other than “it’s done”, before it keeps going.
For sending the jobs to the worker thread, I think a ring buffer or similar standard fan-in setup would perhaps be a good approach? But for a Job Creator to find out that her job has been done, I’m not so sure..
The job creators could sleep, and the worker interrupt them when done.. Or each job creator could have an atomic boolean that it checks, and that the worker sets. I dunno, neither of those feel very nice. I’d like to do it with as few (none, if possible) locks as absolutely possible. So to be clear: What I’m looking for is speed, not necessarily simplicity.
Does anyone have any suggestions? Links to reading about concurrency strategies would also be very welcome!
There’s a couple ways to do this. The fastest way would probably be to just use
Semaphoreand a single-threaded executor.Then in the Job class:
Semaphoreis decently fast, much faster than usingsynchronizedblocks.Edit: I should also note that this avoids a lot of overhead from
Future, and so is probably also faster than theFutureimplementation suggested by others, but without testing it myself, I can’t be sure.