I need to execute some amount of tasks 4 at a time, something like this:
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
taskExecutor.execute(new MyTask());
}
//...wait for completion somehow
How can I get notified once all of them are complete? For now I can't think about anything better than setting some global task counter and decrease it at the end of every task, then monitor in infinite loop this counter to become 0; or get a list of Futures and in infinite loop monitor isDone for all of them. What are better solutions not involving infinite loops?
Thanks.
This is my solution, based in "AdamSkywalker" tip, and it works
You could wrap your tasks in another runnable, that will send notifications:
Follow one of below approaches.
submit
onExecutorService
and check the status with blocking callget()
onFuture
object as suggested byKiran
invokeAll()
on ExecutorServiceshutdown, awaitTermination, shutdownNow
APIs of ThreadPoolExecutor in proper sequenceRelated SE questions:
How is CountDownLatch used in Java Multithreading?
How to properly shutdown java ExecutorService
Just to provide more alternatives here different to use latch/barriers. You can also get the partial results until all of them finish using CompletionService.
From Java Concurrency in practice: "If you have a batch of computations to submit to an Executor and you want to retrieve their results as they become available, you could retain the Future associated with each task and repeatedly poll for completion by calling get with a timeout of zero. This is possible, but tedious. Fortunately there is a better way: a completion service."
Here the implementation
There is a method in executor
getActiveCount()
- that gives the count of active threads.After spanning the thread, we can check if the
activeCount()
value is0
. Once the value is zero, it is meant that there are no active threads currently running which means task is finished:you should use
executorService.shutdown()
andexecutorService.awaitTermination
method.An example as follows :