I'm using a PriorityBlockingQueue<T> q
to handle parallel processing of tasks. The queue is initialized by some tasks, and the processing of each task may produce some more tasks, that will be added to the queue. I want to process the tasks in parallel, and stop when all the tasks have been processed. Of course the queue may temporarily become empty before we're done, if tasks are still being processed by other threads.
My question is: what's a good (correct, of course, but also elegant, idiomatic, with no unnecessary locking or waiting when the queue is empty) way to do this in Java?
Notes:
I'm using a priority queue, but the tasks may be processed in any order (there's some gain in handling the tasks in roughly the order specified by the priority - but I think it's safe to just ignore this bit).
This answer ("use the Task Parallel Library") seems to address the issue for C#, but it seems that this doesn't exist for Java. This is essentially the same question; it does not seem to have a completely satisfactory answer...
The processing of each task is quite lengthy, so it's ok to have a bit more overhead for the task management if it makes the code more elegant (and that's also why I'm happy to have a single thread in charge of polling tasks from the queue and assigning them to the workers)
Example: As a rough approximation, I'm trying to use parallel BFS to find the depth of a tree that's dynamically generated. You can think of it as looking for a strategy that will maximize your reward while playing a game, where you get a point for every move you make. Each state is a task to be processed. You start at the initial (root) state, you compute all the moves (this computation is lengthy and may generate thousands of moves), and add the states reached by these moves as tasks to be explored.