Lesson · Executors, Thread Pools & Async Programming
ExecutorService: submit, shutdown and the lifecycle
15 min readExecutorService
ExecutorService is where a pool stops being a shared utility and becomes a resource you own. Tasks go in through execute, submit, invokeAll or invokeAny, results come out through Futures, and the pool itself ends through one of two exits: shutdown drains the queue, shutdownNow interrupts what runs and hands back what never started. Half the interface is that ending.
The pool that cannot outlive the request
Here is a pool that does real work and cannot exist safely: created inside a request handler, used for a single task, never shut down.
The worker it created stays alive, parked on a queue that will never receive another task, and because executors create non-daemon threads by default, the JVM will not exit while that worker exists. One pool per request means one leftover thread per request: the leak shows up as thread count and memory, long after the call that caused it.
The interface treats this as a first-class problem, so lifecycle sits on ExecutorService itself, next to submission. The surface worth knowing is small: tasks in through execute, submit, invokeAll and invokeAny, results out through Future and CompletionService, and an ending that is spelled out by shutdown, shutdownNow, awaitTermination, isShutdown, isTerminated and close.
public Response handle(Request request) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(4); // a pool per call Future<Response> future = pool.submit(() -> process(request)); return future.get(); // and it is never shut down }
| Call | What it does | Where the result lives |
|---|---|---|
| execute(Runnable) | runs one task, no value expected | nowhere: failures reach the worker's handler chain (Uncaught Exception Handler lesson) |
| submit(Runnable or Callable) | runs one task | a Future: value, failure or cancellation |
| invokeAll(tasks) | runs a batch and waits | one Future per task, in submission order |
| invokeAny(tasks) | races equivalent attempts | the first successful result; the rest are cancelled |
| shutdown() and shutdownNow() | end the pool: drain, or interrupt and return the queue | the queue: drained in the first case, handed back in the second |
| awaitTermination(t) | waits for the ending | true when the pool has finished everything |
| close() (AutoCloseable, Java 19+) | shutdown, then waiting, for a block-scoped pool | nothing to collect: the block cannot exit early |
A pool you never shut down outlives the work. Its workers are non-daemon by default, so the JVM waits for them long after main returns.
Batches: invokeAll and invokeAny
Submitting in a loop and reading the Futures in order is a fine default, but the interface ships two batch calls that name the two common intents. invokeAll(tasks) submits everything and blocks until every task is done, and the returned list holds one Future per task in the same order as the input, which is submission order regardless of who finished first.
invokeAny(tasks) is the opposite intent: hand it a list of equivalent attempts and it returns the result of the first one that completes successfully. As soon as one succeeds, the rest are cancelled; if they all fail, you get an ExecutionException wrapping one of the failures. First result wins is exactly what a hedged read, a multi-mirror fetch or a race between implementations wants.
Both have timed overloads with the same shape: invokeAll with a timeout returns once the time is up and cancels whatever has not finished; invokeAny with a timeout gives up waiting and throws TimeoutException. Mixing the two ideas is where the classic bug lives, because invokeAll asks for all or nothing while invokeAny wants only the winner.
List<Callable<String>> mirrors = List.of( () -> fetch("eu-1"), () -> fetch("us-1"), () -> fetch("ap-1")); String fastest = pool.invokeAny(mirrors); // first success wins, the rest are cancelled List<Future<Report>> reports = pool.invokeAll( accounts.stream().map(a -> (Callable<Report>) () -> buildReport(a)).toList()); for (Future<Report> report : reports) { save(report.get()); // submission order: accounts order is preserved }
| Call | Waits for | Returns | Other tasks |
|---|---|---|---|
| invokeAll(tasks) | every task to finish | a Future per task, in submission order | none left unfinished by the time it returns |
| invokeAll(tasks, timeout) | every task, or the timeout | the same list, some entries cancelled | unfinished tasks are cancelled |
| invokeAny(tasks) | the first successful result | that one result | cancelled as soon as one succeeds |
| invokeAny(tasks, timeout) | the first success, or the timeout | that one result, or TimeoutException | cancelled when the method returns |
invokeAll waits for all and preserves submission order; invokeAny waits for one and cancels the rest.
shutdown(): close the intake, drain the queue
shutdown() is a request, not an interruption. It stops accepting new tasks and returns immediately, while everything already submitted still runs: the running tasks finish, the queue drains in order, and the workers exit when there is nothing left. That is the graceful path, and it is what you want in almost every case.
From the moment shutdown() is called, the pool is closed for business. execute and submit throw RejectedExecutionException, delivered by the same rejection machinery you will meet in the thread pools lesson. isShutdown() reports true immediately, while isTerminated() stays false until the last task has completed and every worker has exited.
The two booleans are positions on a timeline: intake closed, queue drained, workers gone. Nothing can slip between the first two steps, because acceptance ended before the queue was drained, which is precisely the guarantee a service needs while it is shutting down.
shutdown() drains: everything that was accepted runs, and nothing new gets in.
shutdownNow(): interrupt and hand back the queue
shutdownNow() is the escalation. It interrupts the running tasks in place, halts the processing of waiting tasks, and returns a List<Runnable> holding the tasks that were queued but never started. That list is the most important return value in the method, because it is work that will never run unless you do something with it.
The interruption is best effort, and the javadoc says so plainly: there are no guarantees beyond attempts to stop the tasks, and most implementations fall back on Thread.interrupt. A task that ignores interrupts, blocks in uninterruptible IO or swallows the InterruptedException may keep running, so shutdownNow cannot promise a quiet pool. Wait for isTerminated() before assuming otherwise.
With both methods in view, the contract is one sentence per exit: shutdown drains what was accepted, shutdownNow interrupts what is running and returns what was waiting.
- Log or resubmit the returned list. It is the only record of work the pool was holding when you pulled the plug.
- Rely on interruption, not on force. Cooperative cancellation is the Java model (see the thread api lesson); a task that never checks the interrupt flag never stops.
- Expect the boundary to be a race. A task that started a moment before the call is interrupted rather than returned, and a task that finished on its own simply finished. The returned list is a snapshot, not a promise about everything uncompleted.
shutdownNow does not undo the past: it interrupts what is running and hands you what never started.
Pool of 2 · five tasks
tasks
close the intake, drain the queue
A pool of two workers, five tasks submitted: a and b are running, c, d and e wait in the queue in submission order. The badge reads RUNNING and the intake is open.
Waiting, checking, and closing with try-with-resources
Neither shutdown method waits, so the third piece of the lifecycle is the one that does. awaitTermination(timeout) blocks until the pool has finished everything or the timeout expires, returning true in the first case and false in the second, and it can throw InterruptedException if the waiting thread is cancelled. The graceful shutdown idiom is that sequence: call shutdown, wait with a budget, escalate with shutdownNow if the budget runs out.
The state checks complete the picture. isShutdown() is true from the moment you ask, isTerminated() is true only when all tasks have completed following shutdown and the workers have exited, and isTerminated() is documented never to be true unless one of the two shutdown methods was called first. A pool that is merely quiet is not a pool that is finished.
Since Java 19, ExecutorService extends AutoCloseable, so try-with-resources works for block-scoped pools. The default close() performs shutdown() and then waits for termination; if the waiting thread is interrupted it escalates to shutdownNow() rather than leaving the work half-finished. For a pool that lives as long as the application, the same contract belongs in a shutdown hook or a framework destroy method.
| Call | Stops the intake | Interrupts running tasks | Returns |
|---|---|---|---|
| shutdown() | yes | no | void, immediately |
| shutdownNow() | yes | yes, best effort | the tasks that never started |
| awaitTermination(t) | no, it only waits | no | true if terminated within the budget |
| close() (Java 19+) | yes, through shutdown | only if the waiter is interrupted | void, after termination |
shutdown() drains, shutdownNow() interrupts and hands back the queue, and awaitTermination is how you wait for either to finish.
ExecutorService lifecycle
one intake, two exits, one terminal state
RUNNING
accepts tasks; isShutdown false, isTerminated false
SHUTTING DOWN
intake closed; submissions throw RejectedExecutionException
TERMINATED
isTerminated true; the resource is finally gone
The first transition is one-way: no executor restarts, and a new pool is the only way back to RUNNING. isShutdown() turns true at the first arrow, isTerminated() only at the second.
shutdown()
close the intake, let the queue drainRunning tasks finish first, then every queued task runs in submission order. awaitTermination returns true after the last worker exits.
shutdownNow()
interrupt the running work, return the waiting workThe returned list is the only record of work that never started: log it, resubmit it, or accept the loss on the record rather than by accident.
The graceful shutdown idiom, as steps
Put together, the sequence is short enough to memorise and mechanical enough to script. The only judgement is the budget in the middle, and the only rules are that every step has a fallback and the caller never blocks forever.
- Stop accepting work with shutdown(). New submissions fail fast with RejectedExecutionException, which is the signal that the door is closed.
- Wait with a budget: awaitTermination(30, TimeUnit.SECONDS), sized to the slowest task you actually expect rather than to a mood.
- Escalate if the budget expires: shutdownNow(), then read the returned list and decide, because work that never started is a decision rather than an accident.
- Give interruption a brief final grace period: awaitTermination again, and log if the pool still refuses to terminate. A worker stuck in uninterruptible IO will not come back, and that is information.
- Keep the executor reference somewhere sensible: an application shutdown hook, a framework destroy method, or a try-with-resources block. Every path that creates a pool needs a path that closes it.
Every pool needs one owner and one shutdown path; a pool with neither is a leak with a schedule.
CompletionService: results as they finish
One more tool earns its place here. Reading invokeAll Futures in submission order is wrong when task durations differ, because the slow first task holds back four finished results. ExecutorCompletionService wraps an existing executor and its take() hands you the next Future that has completed, whichever task that was.
You submit through the completion service rather than the executor, and consume through take(), which blocks until something is done, or poll(), which returns null or a finished Future. The pool underneath stays an ordinary executor, so its lifecycle rules are unchanged: shut down the executor you passed in, not the wrapper.
CompletionService<Result> completed = new ExecutorCompletionService<>(pool); for (Task task : tasks) { completed.submit(() -> run(task)); } for (int i = 0; i < tasks.size(); i++) { results.add(completed.take().get()); // completion order, not submission order }
When task times differ, consume in completion order: CompletionService is the adapter that lets you.
Remember
Submit means the pool owns the work now: it finishes what it accepted, in queue order, and failures arrive through a Future or the worker's handler chain, never as a lost exception.
Shutdown means that ownership ends on your terms. shutdown drains, shutdownNow interrupts and returns the queue, awaitTermination is how you wait, and isTerminated is the only proof that the pool is really gone.
Lifecycle is half the interface: a pool exists to be drained and closed, not to live alongside the process.
The list nobody read
A deploy script called shutdownNow() on a batch pool and moved on. Tasks that had been queued were returned as a List that nothing read, so the lost work was invisible until someone compared database rows. shutdownNow can only interrupt what is running; everything that was waiting comes back to you, and the returned list is the only copy. Read it, log it, resubmit it, or call shutdown() and let the queue drain instead.
Interview angles
What is the difference between shutdown() and shutdownNow()?+
shutdown() stops accepting tasks and lets everything already submitted finish, so the queue drains. shutdownNow() interrupts the running tasks and returns the queued ones in a List, so the caller owns whatever never started.
Common misconception: shutdown() is expected to cancel queued work. It does the opposite: the queue is exactly what it finishes.
Why does submit() exist if execute() can run any Runnable?+
submit returns a Future, so it can carry a result, a captured failure or a cancellation, and it also accepts Callable. The failure routing difference between the two is owned by the Uncaught Exception Handler lesson: execute reports through the worker's handler chain, submit stores the throwable in the Future.
submit(Runnable) gives you a Future whose value is null, which is still useful: cancellation and completion observation come with it. submit(Callable) is the one that returns a value and can throw checked exceptions.
invokeAll or invokeAny: how do you choose?+
invokeAll is for a batch where every result matters, and it returns Futures in submission order once all tasks finish. invokeAny is for equivalent attempts where the fastest success is the answer, and it cancels the rest as soon as one succeeds.
Both have timed overloads. The timed invokeAll cancels whatever has not finished when the timeout expires; the timed invokeAny throws TimeoutException if nobody succeeded in time.
How do you shut a pool down gracefully?+
shutdown(), then awaitTermination with a budget, then shutdownNow() if the budget expires, then check the returned list and the pool state. The short version: stop the intake, wait, escalate, and never block forever.
Follow-up: Where does that owner live in a Spring application, and what happens if the JVM is killed before it runs?
What does isTerminated() guarantee, and what does it not?+
It guarantees that all tasks have completed following a shutdown request and that the workers have exited. It never returns true unless shutdown or shutdownNow was called first, and it says nothing about the tasks that shutdownNow returned to you.
Common misconception: A quiet, idle pool is assumed to be terminated. A pool with no work is still RUNNING until someone closes it.
A batch mixes slow and fast tasks and you want partial results early. What do you reach for?+
A CompletionService. ExecutorCompletionService wraps your pool, and take() hands you the next completed Future regardless of submission order, so a slow first task cannot hold back finished results.
For full non-blocking composition, the CompletableFuture lesson later in this part goes further: stages, combinations and retries without dedicating a thread to waiting.