Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 InterruptedException

Examples

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 shutdown

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.