Practical technical guides

ExecutorService.close() Waits for Every Task, So Try-With-Resources Can Hang

What close() promises since JDK 19, measured on JDK 23, and how to give executor shutdown an explicit deadline.

By Sandeep Belgavi · Published 2026-12-05

A tidy block that never returns

Since JDK 19, ExecutorService extends AutoCloseable, so a thread pool can live in a try-with-resources block. The code reads well and removes a familiar leak: pools that were created per request and never shut down. A batch job at Belgavi's Book Store uses it to fetch cover images for a list of new titles:

try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
    for (String isbn : isbns) {
        pool.submit(() -> covers.fetch(isbn));
    }
}
// the job continues here

One night the job stops making progress. A thread dump shows the main thread inside ExecutorService.close, waiting. One cover request is stuck on a socket read without a timeout. The block will not exit until that request finishes, because that is exactly what close is specified to do.

What close() promises

The JDK 23 API documentation describes the default close method as an orderly shutdown: it initiates a shutdown in which previously submitted tasks are executed but no new tasks are accepted, and then waits if necessary for all tasks to complete. If the thread calling close is interrupted while waiting, it stops all executing tasks as if by shutdownNow, and then continues to wait until all actively executing tasks have completed. Tasks still awaiting execution are not executed. The interrupted status is re-asserted before the method returns.

Three consequences follow, and each surprises someone:

  • Queued tasks run. Leaving the block does not discard work that was submitted but not started. A single-threaded pool with four queued 300 ms tasks takes about 1.2 seconds to close.
  • There is no timeout. close waits as long as it takes. A task that blocks forever makes close block forever.
  • Interruption only helps interruptible tasks. After an interrupt, close cancels running tasks with interrupts and keeps waiting. A task that ignores interrupts, such as a busy loop or a read on a socket without a timeout, still holds close open.

Measured on JDK 23

A small probe program checks each claim on a local JDK 23.0.2. The tasks are synthetic sleeps and loops; the timings are single runs on one machine and are only meant to confirm the specified behaviour.

ScenarioWhat the probe didObserved
Slow taskTwo-thread pool, one 800 ms task, then closeclose returned after 823 ms
Queued tasksSingle thread, four 300 ms tasks, then closeall 4 ran, 1,254 ms
Interrupt, cooperative taskTask sleeps 5 s, caller interrupted at 300 msclose returned at 317 ms, task saw the interrupt
Interrupt, busy taskTask spins for 1.2 s ignoring interrupts, caller interrupted at 300 msclose returned at 1,203 ms
Bounded shutdownshutdown, wait 500 ms, then shutdownNowreturned at 504 ms, task interrupted
Virtual threads1,000 tasks of 400 ms on a virtual-thread-per-task executorclose returned at 486 ms

In both interrupt scenarios, the interrupted flag was set again when close returned, as specified. The busy-task row is the one to remember: interrupting the caller did not shorten the wait at all.

Choose the shutdown policy explicitly

Try-with-resources is the right shape when every task is bounded, either because it has its own timeout or because its work is local and finite. When a task can block on something outside the process, the shutdown needs a deadline that someone chose:

static void shutdownWithin(ExecutorService pool, Duration grace, Duration hard) throws InterruptedException {
    pool.shutdown();                                   // stop accepting, let queued work run
    if (pool.awaitTermination(grace.toMillis(), TimeUnit.MILLISECONDS)) return;
    List<Runnable> neverStarted = pool.shutdownNow();  // interrupt running, drop queued
    log.warn("{} queued tasks dropped", neverStarted.size());
    if (!pool.awaitTermination(hard.toMillis(), TimeUnit.MILLISECONDS)) {
        log.error("tasks ignored interruption; threads still running");
    }
}

This is the pattern the ExecutorService documentation has long shown in its usage example, with two decisions made visible: how long queued work may keep running, and what happens to tasks that never started. The list returned by shutdownNow is the work that was dropped; record it, because the job's output is incomplete.

The policy does not fix a task that ignores interruption. Only the task can fix that. Give every blocking call its own timeout: connect and read timeouts on HTTP clients, Future.get with a timeout, query timeouts on database statements. Then the pool's shutdown deadline is a backstop rather than the only defence.

Where it bites in services

Request-scoped pools. A web handler that creates a pool in try-with-resources to fan out three downstream calls blocks the request thread until all three finish, even after it has the answer it needed from the first. If the client has already given up, the server is still holding a thread. Use a shared, bounded pool and cancel the remaining futures when the answer is complete, or use structured concurrency (still a preview API in JDK 23), which ties subtask lifetimes to the scope and cancels unfinished subtasks when the scope closes on failure.

Shutdown hooks. A shutdown hook that closes a pool can delay process exit indefinitely, and an orchestrator then kills the process after its grace period, losing whatever the hook was trying to flush. Put a deadline inside the hook that is shorter than the platform's grace period.

Virtual threads. A virtual-thread-per-task executor makes it cheap to start a thread per task, and its close still waits for all of them. A thousand sleeping tasks closed in under half a second in the probe because they all slept concurrently; a thousand tasks blocked on an unresponsive dependency close when the dependency answers.

Scheduled executors. A ScheduledThreadPoolExecutor keeps delayed tasks after shutdown by default: its getExecuteExistingDelayedTasksAfterShutdownPolicy is true, while periodic tasks are cancelled at shutdown. Closing a scheduled pool therefore waits for every one-shot task that is still in its delay. In a second probe on the same JDK, closing a pool holding one task scheduled 1,500 ms ahead took 1,517 ms and ran the task. With setExecuteExistingDelayedTasksAfterShutdownPolicy(false) the same close returned in about 1 ms and the task never ran, and a pool holding only a fixed-rate task also closed in about 1 ms. A reminder service that schedules follow-ups hours ahead and closes its pool in a shutdown hook will hold the process open for hours, or until the orchestrator kills it. Decide whether pending delayed work should run, be dropped or be persisted elsewhere; for anything that matters after a restart, an in-memory delay queue is the wrong store anyway.

The common pool. The documentation notes that close has no effect on ForkJoinPool.commonPool(). Code that closes whatever executor it was given and expects the work to be finished afterwards does not get that guarantee from the common pool.

Failure modes

A hung batch with no error. The job is waiting by design; no exception is thrown and nothing is logged. A thread dump showing close or awaitTermination is the signature.

Lost work hidden by shutdownNow. Dropping queued tasks without logging them produces silently partial output.

Swallowed interrupts. A task that catches InterruptedException and continues defeats both close and shutdownNow. Restore the interrupt flag or exit.

Double waiting. A caller that closes a pool and then calls get on every future waits twice; harmless, but it hides which wait was slow.

Verification

  • Test that a task blocked on a fake dependency does not keep the pool open beyond the configured deadline, and that the dropped-task count is logged.
  • Test cancellation: interrupt the closing thread and assert that cooperative tasks observe the interrupt.
  • Static check: flag try-with-resources pools whose tasks call network or database clients without explicit timeouts.
  • In production, alert on threads waiting in close or awaitTermination for longer than the expected job duration.

The companion example contains the probe program used for the table, written for JDK 21 or later, with expected-output ranges and a Python harness that compiles and runs it.

Primary references and authorship

Sources read December 5, 2026. Original explanations, measurements and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/java_executor_close. Views are my own and do not represent any employer, past or present.