Reputation: 66166
I have N tasks, I want them to be processed in parallel with N threads. I want to wait until all tasks are finished, store results, and then run next N tasks (and so on in a loop).
Which abstractions from java util concurrency can help me here?
I looked at ExecutorService.invokeAll()
, but it returns a list of futures, so I should iterate all of them in a loop until all of them are done.
I thought, there should be more straightforward way to calculate a set of tasks.
Upvotes: 3
Views: 3830
Reputation: 7940
I would suggest you to use CyclicBarrier. This way you wait till all threads have finished job and then you can start with next set of tasks.
Upvotes: 0
Reputation: 40256
ExecutorService.invokeAll()
is probably the most straightforward way of doing it.
You don't iterate over any of them to await completion. invokeAll
only returns when all of them are completed. So by the time you can iterate over them, get
will return immediately.
Upvotes: 6
Reputation: 476
If you are using JAVA 7, I suggest the Fork/Join framework. I'd explain but this article is much better than anything I can say: http://www.oracle.com/technetwork/articles/java/fork-join-422606.html
Upvotes: 0
Reputation: 597114
You can use ExecutorCompletionService
- it allows you to get Future
s in the order they are completed.
You will still have a tiny while loop, and the code you want to invoke after everything is completed will be after the loop. I think that should be ok.
Upvotes: 4