Skip to content
javahacks.dev
Concurrency

ExecutorService Shutdown Without Leaking Threads in Java

Shut down a Java ExecutorService properly with shutdown, awaitTermination and shutdownNow, handle interrupts, and avoid thread leaks in web apps and tests.

7 min read
Summarize in AI
Flat illustration of threads sharing work across lanes, a lock and a pool, with the OpenJDK, Linux and IntelliJ IDEA logos.

A thread pool owns threads. If nobody tells it to stop, its non-daemon threads keep the JVM running after main returns, and in a web application they survive a redeploy and leak the old class loader.

The standard sequence

java
void shutdownAndAwait(ExecutorService pool) {
    pool.shutdown();                                       // reject new tasks, run queued ones
    try {
        if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
            pool.shutdownNow();                             // interrupt running tasks
            if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
                log.warn("pool did not terminate");
            }
        }
    } catch (InterruptedException e) {
        pool.shutdownNow();
        Thread.currentThread().interrupt();                 // keep the interrupt status
    }
}

This is the pattern from the ExecutorService Javadoc. After shutdown(), submit throws RejectedExecutionException. awaitTermination returns true if the pool terminated within the time, so check the result. shutdownNow() attempts to stop actively running tasks by interrupting their threads and returns the list of queued tasks that never ran, which you may want to log or persist.

Try-with-resources on JDK 19 and later

java
try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
    futures = tasks.stream().map(executor::submit).toList();
}   // close() waits for all tasks, then terminates

close() calls shutdown() and waits until tasks complete, interrupting if the waiting thread is interrupted. It suits scoped work, such as one batch job. It waits without a time limit, so tasks must be able to finish.

Interruption is cooperative

shutdownNow() only sets the interrupt flag. A task that loops forever without checking it is not stopped:

java
executor.submit(() -> {
    while (!Thread.currentThread().isInterrupted()) {
        process(queue.poll(1, TimeUnit.SECONDS));       // blocking calls throw InterruptedException
    }
});

Blocking methods like sleep, wait, BlockingQueue.take and I/O on interruptible channels throw InterruptedException. Do not swallow it:

java
catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    return;
}

A task blocked in a plain InputStream.read or a synchronized block ignores interrupts until it returns, and that is when a pool "hangs" at shutdown. A thread dump shows which task still runs, see using jcmd and jstack.

Where leaks come from

  • A pool per call. new Thread factories or Executors.newFixedThreadPool inside a method create fresh threads on every call. Share one pool, or close it in finally.
  • Tests. A test that creates an executor and forgets it leaves threads for the whole JVM. Close it in @AfterEach.
  • Web redeploys. Pools started by the application that outlive a redeploy retain the old classes, a cause of Metaspace growth, see Metaspace and class loader leaks.
  • Scheduled pools. A ScheduledExecutorService with a periodic task never terminates on its own.

Tie it to a lifecycle

In Spring, expose the executor as a bean and let the container shut it down:

java
@Bean(destroyMethod = "shutdown")
ExecutorService reports() { return Executors.newFixedThreadPool(4); }

Spring's ThreadPoolTaskExecutor has setWaitForTasksToCompleteOnShutdown(true) and setAwaitTerminationSeconds. In a servlet container, shut down in a ServletContextListener.contextDestroyed. For containers, the termination signal and grace period are in handling signals.

Daemon threads

Making pool threads daemon lets the JVM exit regardless, at the cost of cutting tasks short at exit. Choose that for background housekeeping, not for work that must finish, and name the threads, as in ThreadFactory.

What a leaked pool does to a process

A pool that is never shut down keeps its threads alive, and a live non-daemon thread keeps the JVM from exiting. This program submits one task to a fixed pool and returns from main.

Leak.javajava
public static void main(String[] args) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(2);
    pool.submit(() -> System.out.println("work done on " + Thread.currentThread().getName()));
    System.out.println("main finished");
    if (args.length > 0) pool.shutdown();
}
Text
$ timeout 3 java Leak
main finished
work done on pool-1-thread-1
(still running after 3 seconds, killed: exit status 124)

$ java Leak yes
main finished
work done on pool-1-thread-1
(exit status 0)

Without shutdown(), the process printed everything it had to say and then sat there until timeout killed it. A command-line tool does this as an annoyance. A web application in a servlet container does it as a leak: redeploying the application starts a new pool while the old one's threads keep the old class loader alive, which is a standard route to a metaspace leak. The cure is the same in both: whoever creates the pool owns its shutdown.

The two-phase stop, with an uncooperative task

shutdown() lets queued work finish and stops accepting new work. shutdownNow() interrupts running tasks and returns the ones that never started. The standard sequence uses both, with a wait between them. The program below runs it against two pools, one whose task respects interruption and one whose task does not.

Shut.javajava
static void stop(ExecutorService pool) {
    pool.shutdown();
    try {
        if (!pool.awaitTermination(1, TimeUnit.SECONDS)) {
            var dropped = pool.shutdownNow();
            System.out.println("forced, never started: " + dropped.size());
            if (!pool.awaitTermination(1, TimeUnit.SECONDS)) System.out.println("still running after interrupt");
        }
    } catch (InterruptedException e) {
        pool.shutdownNow();
        Thread.currentThread().interrupt();
    }
}
Text
forced, never started: 1
polite task saw interrupt
forced, never started: 0
still running after interrupt
main done

For the first pool, a task sleeping for a minute was interrupted when shutdownNow() ran, and the queued task behind it never started, so one task was returned. For the second pool, the task was a busy loop that never checks the interrupt flag, and shutdownNow() could do nothing: the thread kept running to the end of its three seconds, and the program reported it. The lesson is in the second half. Interruption is a request. A task that loops must test Thread.currentThread().isInterrupted() or call a method that throws InterruptedException, or it cannot be stopped.

java
while (!Thread.currentThread().isInterrupted() && it.hasNext()) {
    process(it.next());
}

Return the dropped work to its owner

shutdownNow() returns the list of tasks that were queued and never started. Throwing that list away loses work silently. At minimum log its size, as above. For work that matters, such as emails to send, persist the tasks before submitting them and mark them done on completion, so a forced shutdown loses nothing and the next start resumes from the table. The pool is not a durable queue and should not be treated as one.

Let the framework call shutdown

Calling shutdown() by hand in every class is how a pool gets forgotten. In a Spring application, declare the executor as a bean and let the container stop it. Spring infers the shutdown method for @Bean declarations, and ThreadPoolTaskExecutor exposes the wait explicitly.

java
@Bean
ThreadPoolTaskExecutor invoiceExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(4);
    executor.setMaxPoolSize(4);
    executor.setQueueCapacity(100);
    executor.setThreadNamePrefix("invoice-");
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setAwaitTerminationSeconds(20);
    return executor;
}

With server.shutdown=graceful set, the web server stops accepting requests, finishes the ones in flight, and then the context closes the executor, waiting up to twenty seconds. Make the Kubernetes terminationGracePeriodSeconds larger than the sum of those two waits, or the container is killed in the middle of the drain.

Choosing the waiting times

The two waits in the sequence are not arbitrary numbers. The first, after shutdown(), should be as long as the longest task you are willing to let finish, since this is the period in which the queue drains normally. For a request-processing pool that is a few seconds; for a batch worker it may be the length of one batch. The second, after shutdownNow(), only needs to be long enough for tasks that respond to interruption to notice it and exit, which is usually well under a second. A task that is still running after that wait is a bug to fix in the task, not a reason to wait longer.

Set both from the same source as the environment's termination budget. A Kubernetes pod gets thirty seconds by default between SIGTERM and SIGKILL, and everything in the application's own shutdown, the web server drain, the pools, the connection pool close, has to fit inside it. Add the three numbers up. If they exceed the budget, the process will be killed in the middle of the sequence, and the log will end without any of your shutdown messages, which is itself a useful diagnostic: it means the budget was too small.

Where this does not apply

For virtual threads, the executor is lightweight, and close() still waits for the tasks. Basics are in ExecutorService usage. The reference is the [ExecutorService Javadoc](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/ExecutorService.html), and thread interruption is in the Java tutorials.

Also inDebugging
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.