Skip to main content
Executors and thread pools · Topic 6 of 7

Graceful shutdown

Definition​

Always shut an executor down, or its threads keep the program alive. shutdown() stops accepting new tasks and lets queued ones finish. awaitTermination waits. If tasks take too long, shutdownNow() interrupts them.

Example code​

The standard shutdown sequence

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Demo {
static void shutdown(ExecutorService pool) throws InterruptedException {
pool.shutdown(); // 1. stop accepting new tasks
if (!pool.awaitTermination(1, TimeUnit.SECONDS)) { // 2. give running tasks time to finish
pool.shutdownNow(); // 3. interrupt whatever is still running
pool.awaitTermination(1, TimeUnit.SECONDS);
}
}

public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("quick task done"));
pool.submit(() -> {
try { Thread.sleep(10_000); } // a task that is too slow
catch (InterruptedException e) { System.out.println("slow task was interrupted"); }
});

Thread.sleep(100);
shutdown(pool);
System.out.println("terminated: " + pool.isTerminated());
}
}

// Output:
// quick task done
// slow task was interrupted
// terminated: true

Finished this page? Track your progress (saved only in your browser).