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

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


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) {  ...}


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();


ExecutorService.invokeAll() does it for you.

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);List<Callable<?>> tasks; // your tasks// invokeAll() returns when all tasks are completeList<Future<?>> futures = taskExecutor.invokeAll(tasks);