1

Possible Duplicates:
ExecutorService, how to wait for all tasks to finish
Java ExecutorService: awaitTermination of all recursively created tasks

Is there a way to block the current thread until an ExecutorService has finished all its tasks?

executor.execute(task1);
executor.execute(task2);
executor.execute(task3);
executor.execute(task4);
executor.execute(task5);
// ...now I want to block until all tasks have finished executing...
System.out.println("done!")
Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • use `invokeAll`, and then call `get` on the returned `Future` objects...it's analogous to `Thread.join()`. – mre Jun 16 '11 at 15:55

2 Answers2

7

For all your tasks, put them into a List callables then invokeAll on them

ExecutorService e = ...

e.invokeAll(callables);

Per javadocs

Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

Thus the thread will wait until all tasks haven been completed

John Vint
  • 39,695
  • 7
  • 78
  • 108
3

You can use a ThreadPoolExecutor with a pool size set to System.getRuntime().availableProcessors()Java 6 or Runtime.getRuntime().availableProcessors()Java 8 and .execute() it all the tasks you want to execute, then call tpe.shutdown() and then wait in a while(!tpe.terminated()) { /* waiting for all tasks to complete */} which blocks for all the submitted tasks to complete. where tpe is a reference to your ThreadPoolExecutor instance.

Or if it is more appropriate use an ExecutorCompletionService A CompletionService that uses a supplied Executor to execute tasks. This class arranges that submitted tasks are, upon completion, placed on a queue accessible using take. The class is lightweight enough to be suitable for transient use when processing groups of tasks.