I'd like to allow the program continue until all the tasks in ExecutorService is done. And I don't want to shutdown it, I use it later. How can I achieve this ? Thanks
Asked
Active
Viewed 44 times
2 Answers
0
Use ExecutorService#shutdown()
followed by ExecutorService#awaitTermination()
to make your main
thread wait for all the submitted tasks to complete before it exits. From the docs for
ExecutorService#awaitTermination()
Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Ravi K Thapliyal
- 51,095
- 9
- 76
- 89
0
An example taken directly from the ExecutorService
Javadoc:
http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html
The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:
void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(60, TimeUnit.SECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}

The111
- 5,757
- 4
- 39
- 55