ExecutorService.shutdown()
Closes the pool to new tasks and lets accepted ones finish.
Available since: Java 1.5
Syntax
void shutdown()
List<Runnable> shutdownNow()
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedExceptionExamples
The classic way to close a pool:
void main() throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
var counter = new AtomicInteger();
for (int i = 0; i < 5; i++) {
pool.submit(counter::incrementAndGet);
}
pool.shutdown();
boolean finished = pool.awaitTermination(5, TimeUnit.SECONDS);
IO.println(finished + " " + counter.get());
try {
pool.submit(() -> {});
} catch (RejectedExecutionException e) {
IO.println("rejected after shutdown");
}
}Output:
true 5
rejected after shutdownNotes
shutdown() does not wait — awaitTermination() does the waiting. shutdownNow() interrupts running tasks and returns those that have not started. Since Java 19 try-with-resources, which calls close(), is simpler than this pair.
See also
- ExecutorService.close() — Closes the pool and waits for all tasks; called automatically by try-with-resources.
- ExecutorService — A service that runs tasks on a pool of threads.
- Executors.newFixedThreadPool() — Creates a pool with a given number of threads.
In the tutorial
- Thread pools and ExecutorService — ExecutorService in Java — thread pools, submit, Callable and Future, invokeAll, handling errors in tasks, timeouts and closing the pool.