Skip to lesson

Shut down a pool correctly

An ExecutorService keeps its threads alive until you tell it to stop. Shutting down a pool means it refuses new tasks, finishes or drops the tasks it already has, and lets its threads end so the program can exit.

Why the program does not exit

A non-daemon thread keeps the JVM running until it ends. Pool threads are non-daemon, so a pool that is never shut down stops the program from exiting.

The JVM exits only when every non-daemon thread has ended. A daemon thread is a background helper that does not keep the JVM alive; normal threads do. Threads made by the Executors factory methods are normal, non-daemon threads.

Example 1 · The worker is still alive after the work is done

WorkerAliveDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;
public class WorkerAliveDemo {    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(1);        Future<Thread> f = pool.submit(() -> {            System.out.println("Result published for roll 42");            return Thread.currentThread();             // hand back the worker thread        });        Thread worker = f.get();
        Thread.sleep(100);        System.out.println(worker.getName() + " alive after its task: " + worker.isAlive());        System.out.println(worker.getName() + " is daemon: " + worker.isDaemon());
        pool.shutdown();        pool.awaitTermination(5, TimeUnit.SECONDS);        worker.join(1000);                             // give the thread a moment to end        System.out.println(worker.getName() + " alive after shutdown: " + worker.isAlive());    }}
Output
Result published for roll 42
pool-1-thread-1 alive after its task: true
pool-1-thread-1 is daemon: false
pool-1-thread-1 alive after shutdown: false

What this code does

  • The only task finished long ago, yet pool-1-thread-1 is still alive, waiting for more work. It is not a daemon thread, so without shutdown() this program would never exit.
  • After shutdown() and awaitTermination, the worker thread ends and the JVM can exit normally when main returns.

After its last task, a pool thread does not end. It waits for the next task, for ever in a fixed pool. So when main returns, these waiting threads keep the JVM running, and the program seems to hang with nothing happening. The fix is to shut the pool down when you have no more work for it. Making pool threads daemon is not a fix: the JVM could then exit in the middle of a task, such as half-way through saving a file.

Find the bug

Find the shutdown mistake

Select the line that is wrong.

The invoices are emailed, but the program never exits. Tap the line that is missing its partner.

Round 1 of 4

shutdown(), awaitTermination() and shutdownNow()

These three methods, plus two checks, control how a pool stops.

Example 2 · shutdown finishes queued tasks and rejects new ones

OrderlyShutdownDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.TimeUnit;
public class OrderlyShutdownDemo {    static void printTicket(int n) {        try {            Thread.sleep(100);                          // the printer is slow        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }        System.out.println("Printed hall ticket " + n);    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService printer = Executors.newSingleThreadExecutor();        for (int n = 1; n <= 3; n++) {            int ticket = n;            printer.submit(() -> printTicket(ticket));        }
        printer.shutdown();                             // returns at once        System.out.println("shutdown() called. isShutdown=" + printer.isShutdown()                + ", isTerminated=" + printer.isTerminated());        try {            printer.submit(() -> printTicket(4));        } catch (RejectedExecutionException e) {            System.out.println("Ticket 4 rejected: the pool is shutting down");        }
        boolean finished = printer.awaitTermination(5, TimeUnit.SECONDS);        System.out.println("All done: " + finished + ", isTerminated=" + printer.isTerminated());    }}
Output
shutdown() called. isShutdown=true, isTerminated=false
Ticket 4 rejected: the pool is shutting down
Printed hall ticket 1
Printed hall ticket 2
Printed hall ticket 3
All done: true, isTerminated=true

What this code does

  • shutdown() returns at once while ticket 1 is still printing. The pool is shut down but not terminated, and the new ticket 4 is rejected.
  • The three tickets submitted before the shutdown are all printed. awaitTermination waits for them and returns true; only now is isTerminated() true.

Example 3 · shutdownNow interrupts and hands back the queue

ShutdownNowDemo.javaJava
import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class ShutdownNowDemo {    static void longReport(String name) {        try {            Thread.sleep(2000);                         // a 2-second report            System.out.println(name + " finished");        } catch (InterruptedException e) {            System.out.println(name + " interrupted, stopping early");        }    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService pool = Executors.newSingleThreadExecutor();        pool.submit(() -> longReport("Attendance report"));        pool.submit(() -> longReport("Fee report"));        pool.submit(() -> longReport("Marks report"));        pool.submit(() -> longReport("Library report"));
        Thread.sleep(100);                              // the first report is running        List<Runnable> neverStarted = pool.shutdownNow();        boolean finished = pool.awaitTermination(1, TimeUnit.SECONDS);
        System.out.println("Never started: " + neverStarted.size() + " tasks");        System.out.println("Terminated: " + finished);    }}
Output
Attendance report interrupted, stopping early
Never started: 3 tasks
Terminated: true

What this code does

  • shutdownNow() interrupted the running attendance report, so its sleep threw InterruptedException and it stopped early. The other three reports were still in the queue; they were removed and returned in the list, and never ran.
  • The pool terminated within a second instead of after 8 seconds. Main prints after awaitTermination, so the task's line always comes first.
  • shutdown(): an orderly stop. New tasks are rejected with RejectedExecutionException; tasks already running and waiting in the queue still run. It returns at once and does not wait.
  • awaitTermination(timeout, unit): blocks until all tasks have finished after a shutdown, the timeout runs out, or the waiting thread is interrupted. Returns true if the pool has finished.
  • shutdownNow(): an urgent stop. It removes queued tasks and returns them as a List<Runnable>, and interrupts running tasks. A task that ignores interrupts keeps running.
  • isShutdown() is true once a shutdown has started; isTerminated() is true only when all tasks have finished after it.
Neither shutdown method waits. Always follow them with awaitTermination when you need the work to be finished.

The standard shutdown pattern

A two-step shutdown calls shutdown() and waits, then calls shutdownNow() to interrupt the tasks that did not finish in time.

The two-step shutdown is the pattern the ExecutorService documentation recommends. First shutdown() and wait a reasonable time for the tasks to finish. If they do not, shutdownNow() to interrupt them, and wait a little more.

Java
static void shutdownAndAwait(ExecutorService pool, long ms) {    pool.shutdown();                                        // step 1: no new tasks    try {        if (!pool.awaitTermination(ms, TimeUnit.MILLISECONDS)) {            pool.shutdownNow();                             // step 2: interrupt the rest            if (!pool.awaitTermination(ms, TimeUnit.MILLISECONDS)) {                System.err.println("Pool did not terminate");            }        }    } catch (InterruptedException e) {        pool.shutdownNow();                                 // we were interrupted: stop now        Thread.currentThread().interrupt();                 // and keep the interrupt flag    }}

Example 4 · The two-step pattern with a stuck task

TwoStepShutdownDemo.javaJava
import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;
public class TwoStepShutdownDemo {    static final AtomicBoolean stuckInterrupted = new AtomicBoolean();
    static void sendEmail(int roll) {        try {            Thread.sleep(20);            System.out.println("Email to roll " + roll + " sent");        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    static void stuckUpload() {        try {            Thread.sleep(60_000);                       // waits for a server that never answers        } catch (InterruptedException e) {            stuckInterrupted.set(true);        }    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService pool = Executors.newFixedThreadPool(2);        try {            pool.submit(TwoStepShutdownDemo::stuckUpload);   // thread 1 gets stuck here            for (int roll = 1; roll <= 3; roll++) {                int r = roll;                pool.submit(() -> sendEmail(r));             // thread 2 sends these in order            }        } finally {            pool.shutdown();            if (!pool.awaitTermination(1, TimeUnit.SECONDS)) {                System.out.println("Still busy after 1 s, calling shutdownNow()");                List<Runnable> dropped = pool.shutdownNow();                System.out.println("Tasks never started: " + dropped.size());                System.out.println("Terminated now: " + pool.awaitTermination(1, TimeUnit.SECONDS));            }        }        System.out.println("Stuck upload was interrupted: " + stuckInterrupted.get());    }}
Output
Email to roll 1 sent
Email to roll 2 sent
Email to roll 3 sent
Still busy after 1 s, calling shutdownNow()
Tasks never started: 0
Terminated now: true
Stuck upload was interrupted: true

What this code does

  • Step 1 (shutdown plus a 1-second wait) let the three emails finish, but the upload would have blocked for a minute. Step 2 (shutdownNow) interrupted it, and the second wait returned true at once.
  • The shutdown sits in a finally block, so it would run even if submitting the tasks threw an exception. In real code, pick timeouts that fit the work, often tens of seconds.

If the waiting thread is itself interrupted, cancel everything and restore the interrupt flag.

Put it in one helper method and call it from a finally block, so the pool is stopped even when the code that uses it throws an exception. Pick the first timeout from the work: a few seconds for result emails, perhaps 30 seconds for payment requests that are already in progress.

ExecutorService with try-with-resources (Java 21)

Since Java 19, ExecutorService extends AutoCloseable, so in Java 21, the long-term support release that includes this, you can create a pool in a try-with-resources block. At the end of the block Java calls close() for you.

Example 5 · try-with-resources closes the pool for you

AutoClosePoolDemo.javaJava
// Java 21import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;
public class AutoClosePoolDemo {    public static void main(String[] args) {        AtomicInteger seatsBooked = new AtomicInteger();
        try (ExecutorService counters = Executors.newFixedThreadPool(3)) {            for (int i = 0; i < 200; i++) {                counters.submit(() -> {                    seatsBooked.incrementAndGet();                });            }        }   // close(): shutdown() and wait for all 200 tasks
        System.out.println("Seats booked: " + seatsBooked.get());    }}
Output
Seats booked: 200

What this code does

  • At the closing brace Java calls counters.close(), which shuts the pool down and waits until every task has run. There is no shutdown() or awaitTermination in sight, and none was forgotten.
  • The count is read after the block, so it is always complete. The first line // Java 21 marks code that needs a newer Java: close() on ExecutorService does not exist in Java 17.

close() calls shutdown() and then waits until every task has finished. If the waiting thread is interrupted, it calls shutdownNow(), keeps waiting, and sets the interrupt flag again at the end. This makes the common case short and safe: no forgotten shutdown, and results are complete after the block. The catch is that close() has no time limit, so a stuck task blocks it for ever. When tasks can hang, use the two-step pattern with timeouts instead.

Next step

Check your understanding

12 quick questions