skip to content

What does ExecutorService add over Executor, and how do you shut one down correctly?

level: middleimportance: must knowfreq 68%

answer

  1. Two additions: Futures and a lifecycle
  2. shutdown = no new tasks, finish queued (non-blocking)
  3. shutdownNow = interrupt running, return un-started tasks
  4. awaitTermination = block until done or timeout, returns boolean
  5. Idiom: shutdown → await → shutdownNow → await

basics

~20 s

ExecutorService adds a lifecycle and result-bearing submission (submit returns a Future; invokeAll and invokeAny run batches) to Executor. Shut it down with shutdown() to finish queued work, awaitTermination() to wait with a timeout, then, if it overruns, shutdownNow() to interrupt stragglers.

solid answer

~60 s

Executor only runs tasks. ExecutorService adds result-bearing submission (submit returns a Future; invokeAll and invokeAny run a batch and wait) and a lifecycle, so the pool's threads can be released. The standard graceful shutdown is: call shutdown() — this rejects new submissions but lets already-queued tasks complete — then awaitTermination(timeout) to block until the queue drains or the timeout elapses; if it times out, call shutdownNow() to interrupt running tasks and discard the queue, then await again. shutdownNow() returns the list of tasks that never started, and works by interrupting worker threads — so tasks must honor interruption for it to be effective. This matters because a non-daemon pool's live threads keep the JVM running; forgetting to shut down leaks threads and can hang process exit. The two-phase pattern (shutdown → await → shutdownNow → await) is the idiom the ExecutorService Javadoc shows. Since Java 19 ExecutorService is AutoCloseable, but its close() is not this idiom: it calls shutdown() and waits with no time limit, using shutdownNow() only if the closing thread is interrupted.

go deeper

for a junior

Knows ExecutorService adds Future-returning submit and a lifecycle to Executor, that you must shut the pool down, that shutdown() lets running tasks finish, and that shutdownNow() tries to stop right away.

for a middle

Describes the two-phase graceful idiom (shutdown → awaitTermination → shutdownNow), what each returns, and that an un-shut pool of non-daemon threads can keep the JVM alive.

for a senior

Explains interruption being cooperative (shutdownNow may not stop tasks), awaitTermination's boolean/timeout semantics, isShutdown vs isTerminated, and that try-with-resources (Java 19+) waits with no timeout.

for a principal

Designs lifecycle ownership and graceful-drain policies for services (timeouts, re-submission of returned tasks, interrupt-responsiveness as a task-authoring requirement, JVM-exit/shutdown-hook coordination).

## What ExecutorService adds `Executor` has a single method, `execute(Runnable)`. Its subinterface **`ExecutorService`** adds two groups of methods: - **Result-bearing submission:** `submit(Callable)`, `submit(Runnable)` and `submit(Runnable, result)` return a **`Future`** you can wait on, cancel, or read a failure from; `invokeAll` runs a collection of tasks and waits for all of them, and `invokeAny` waits for one of them to succeed. - **Lifecycle:** `shutdown`, `shutdownNow`, `awaitTermination`, `isShutdown`, `isTerminated`, and since Java 19 `close()`, because it extends `AutoCloseable`. The rest of this answer is about the lifecycle half. ## Why a lifecycle exists The base `Executor` interface can only *run* tasks — it has no notion of stopping. But a real **thread pool** owns long-lived **worker threads**. Those threads must eventually be released, both to free resources and because **non-daemon** threads (what `Executors.defaultThreadFactory()` creates for `newFixedThreadPool` and `newCachedThreadPool`; `ForkJoinPool` workers and virtual threads are daemon) keep the JVM from exiting. So the `ExecutorService` subinterface adds **lifecycle** methods. An ExecutorService is in one of three logical states: **running** (accepting and executing tasks), **shutting down** (no new tasks accepted, draining existing ones), and **terminated** (all tasks done, threads released). ## shutdown() — graceful, orderly ```java void shutdown(); ``` - **Stops accepting new tasks.** Any later `submit`/`execute` is rejected: in a `ThreadPoolExecutor` it goes to the `RejectedExecutionHandler`, whose default (`AbortPolicy`) throws `RejectedExecutionException`. - **Lets already-submitted tasks finish** — both currently running tasks and tasks still waiting in the queue run to completion. - **Does not block.** It returns immediately; the draining happens in the background. ## shutdownNow() — best-effort immediate stop ```java List<Runnable> shutdownNow(); ``` - **Stops accepting new tasks** (same as shutdown). - **Attempts to stop running tasks**: typical implementations, `ThreadPoolExecutor` among them, call `Thread.interrupt()` on each worker. This is *cooperative*: a task only actually stops if it checks `Thread.currentThread().isInterrupted()` or calls a blocking method that throws `InterruptedException` (like `sleep`, `wait`, `take`). A tight CPU loop that ignores interruption will **not** stop. - **Drains the queue** and **returns** the `List<Runnable>` of tasks that were waiting but never started — so the caller can handle or re-submit them. ## awaitTermination() — wait for completion ```java boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; ``` - **Blocks** the calling thread until (a) all tasks have completed and the service is terminated, (b) the timeout elapses, or (c) the waiting thread is interrupted, which throws `InterruptedException`, whichever comes first. - Returns **true** if it terminated within the timeout, **false** if the timeout expired first (tasks still running). - Crucially, awaitTermination does **not** itself initiate shutdown — you must call `shutdown()` or `shutdownNow()` first; otherwise it will just wait out the full timeout and return false. ## The two-phase idiom The `ExecutorService` Javadoc gives this graceful-then-forceful pattern as an example; here it is with a 30-second grace period: ```java void shutdownAndAwait(ExecutorService pool) { pool.shutdown(); // phase 1: stop new work, drain try { if (!pool.awaitTermination(30, TimeUnit.SECONDS)) { pool.shutdownNow(); // phase 2: interrupt stragglers if (!pool.awaitTermination(10, TimeUnit.SECONDS)) { // log: pool did not terminate } } } catch (InterruptedException e) { pool.shutdownNow(); // re-shutdown if WE were interrupted Thread.currentThread().interrupt();// restore interrupt status } } ``` The logic: ask nicely (`shutdown`), give running work a grace period (`awaitTermination`), and if it overstays, interrupt it (`shutdownNow`) and wait briefly again. If our own waiting thread gets interrupted, we force shutdown and restore the interrupt flag (so callers up the stack still see it). ## Inspecting state - `isShutdown()` — true once shutdown/shutdownNow has been called (may still be draining). - `isTerminated()` — true only once all tasks have actually finished after a shutdown. ## Java 19+: AutoCloseable Since Java 19, `ExecutorService` extends `AutoCloseable`, so try-with-resources shuts it down: ```java try (ExecutorService es = Executors.newFixedThreadPool(4)) { es.submit(task); } // close() blocks until tasks finish — no leaked threads ``` The default `close()` is **not** the two-phase idiom above. It calls `shutdown()` and then waits for termination with **no time limit**; only if the closing thread is interrupted does it call `shutdownNow()`, keep waiting for the running tasks, and re-assert the interrupt before returning. A task that never finishes therefore blocks `close()` forever, so a service that needs a deadline still writes the two-phase method. ## The classic bug: forgetting to shut down If you never shut down a pool whose non-daemon threads do not time out (a fixed pool's core threads never do by default), those threads stay alive and **the JVM will not exit** even after `main` returns; a cached pool's idle threads die after 60 seconds, so its JVM exits late rather than never. In long-running servers this is a thread leak: an un-shut-down fixed pool keeps its core threads forever (a `newSingleThreadExecutor` is the exception: its wrapper registers a `Cleaner` that shuts the pool down once the wrapper becomes unreachable). Always pair pool creation with a shutdown (try-with-resources, a `finally`, or a lifecycle hook).

  • Why might shutdownNow() fail to actually stop a running task?
    Because it only interrupts the worker threads. Interruption is cooperative: a task must check Thread.isInterrupted() or call interruptible blocking methods. A CPU-bound loop that never checks the flag ignores the interrupt and keeps running.
  • What does shutdownNow() return and why is it useful?
    It returns the List<Runnable> of tasks that were still queued but never started. The caller can log, persist, or re-submit them elsewhere, avoiding silent loss of pending work.

  • Thinking shutdown() blocks or cancels queued tasks — it returns immediately and lets queued tasks run.
  • Believing shutdownNow() forcibly kills threads — it only interrupts; tasks ignoring interruption keep running.
  • Calling awaitTermination without first calling shutdown — it just waits out the timeout.
  • Assuming isShutdown() means terminated — it only means shutdown was requested; use isTerminated().
  • Forgetting that a fixed pool left running keeps the JVM alive (its non-daemon core threads never time out by default).
  • Assuming try-with-resources close() gives up after a timeout — it waits with no limit; an interrupt only adds shutdownNow() and it keeps waiting.

ExecutorService
Java 1.5
ExecutorService.close via AutoCloseable
Java 19

Assumes JDK 27. ExecutorService has extended AutoCloseable since JDK 19, so try-with-resources and the default close() behave the same on JDK 25 LTS; the lifecycle methods date from Java 5.

context