Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for all threads to finish, using ExecutorService?

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.

like image 590
serg Avatar asked Aug 09 '09 04:08

serg


People also ask

How do I wait till ExecutorService to finish?

When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing. Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.

How do I stop all threads in ExecutorService?

Using shutdownNow() The shutdownNow() is a hard signal to destroy ExecutorService immediately along with stopping the execution of all in-progress and queued tasks. Use this method, when we want the application to stop processing all tasks immediately.

Which method waits till all threads initiated by the service () method have finished?

parallelStream(). forEach(req -> makeRequest(req)); It's super simple and readable. Behind the scenes it is using default JVM's fork join pool which means that it will wait for all the threads to finish before continuing.

How do I make main thread wait for other threads?

The statement “Thread. currentThread(). join()”, will tell Main thread to wait for this thread(i.e. wait for itself) to die.


2 Answers

Basically on an ExecutorService you call shutdown() and then awaitTermination():

ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) {   taskExecutor.execute(new MyTask()); } taskExecutor.shutdown(); try {   taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) {   ... } 
like image 138
cletus Avatar answered Sep 30 '22 17:09

cletus


Use a CountDownLatch:

CountDownLatch latch = new CountDownLatch(totalNumberOfTasks); ExecutorService taskExecutor = Executors.newFixedThreadPool(4); while(...) {   taskExecutor.execute(new MyTask()); }  try {   latch.await(); } catch (InterruptedException E) {    // handle } 

and within your task (enclose in try / finally)

latch.countDown(); 
like image 38
ChssPly76 Avatar answered Sep 30 '22 18:09

ChssPly76