Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write the standard code to shut down an ExecutorService gracefully, and explain what close() added in Java 19 does.

The standard shutdown calls shutdown() so the executor stops accepting tasks and lets queued ones finish, then awaitTermination with a timeout; if that returns false, it calls shutdownNow() to interrupt running tasks and get back the queued ones, and awaits again briefly. If the waiting thread is interrupted, it calls shutdownNow() and restores the interrupt flag. Since Java 19, ExecutorService implements AutoCloseable, and close() shuts down and waits for all tasks to finish, which makes try-with-resources the natural choice for executors scoped to one operation.

Why this question is asked

An executor that is never shut down keeps its threads alive, which can stop the JVM from exiting and leak threads in tests and redeploys. One that is shut down carelessly cuts tasks off in the middle or makes shutdown hang forever. Interviewers ask for the standard code because it is short but every line has a reason, and because close() changed the idiom in recent Java versions. In this answer, we will recap the executor's shutdown states, write the standard method line by line, see what each line protects against, and then look at close() and try-with-resources.

1A Quick Recap of Shutdown States

An ExecutorService moves through a few states. While running, it accepts and runs tasks. After shutdown(), it is shutting down: it accepts no new tasks, rejecting them with RejectedExecutionException, but it still runs the tasks already queued and those in progress. After shutdownNow(), it is stopping: it removes the queued tasks and returns them to us as a list, and it interrupts the threads running tasks. When the last task has finished, the executor is terminated.

Two details matter. shutdown() and shutdownNow() do not wait; they only start the process and return immediately. Waiting is the job of awaitTermination(timeout, unit), which blocks until the executor terminates or the timeout passes and returns true or false. And shutdownNow() can only ask running tasks to stop by interrupting them; a task that ignores interrupts keeps running.

Step throughExecutor states during a graceful shutdown
  1. Runningaccepts and runs tasks
  2. shutdown()no new tasks; queued and running tasks continue
  3. All done within the timeout?awaitTermination(30 s)
    YesTerminatedNoshutdownNow()
  4. shutdownNow()interrupts running tasks, returns the queued ones
  5. Stopped within 5 s more?awaitTermination(5 s)
    YesTerminatedNoLog that tasks ignore interrupts

5 steps in order. Play them, or step through them one at a time.

2The Standard Shutdown Method

Here is the method we write once and reuse. It gives running and queued tasks a fair chance to finish, then forces the issue, and never hangs forever.

Java
static void shutdownAndAwait(ExecutorService pool, Duration grace) {
pool.shutdown(); // 1. stop accepting, let queued tasks run
try {
if (!pool.awaitTermination(grace.toMillis(), TimeUnit.MILLISECONDS)) { // 2. wait up to the grace period
List<Runnable> dropped = pool.shutdownNow(); // 3. interrupt running, take queued
log.warn("{} tasks never started", dropped.size());
if (!pool.awaitTermination(5, TimeUnit.SECONDS)) { // 4. give interrupted tasks a moment
log.error("pool did not terminate"); // some task ignores interrupts
}
}
} catch (InterruptedException e) { // 5. we were interrupted while waiting
pool.shutdownNow();
Thread.currentThread().interrupt(); // keep the interrupt for our caller
}
}
shutdownAndAwait(reportPool, Duration.ofSeconds(30));
// normal case: all tasks finish in 4 s -> returns after 4 s
// slow case: 30 s pass -> shutdownNow(), "12 tasks never started", returns within 5 s

Step 1 is the polite part: no new work, but everything already accepted may finish. Step 2 bounds how long we are willing to wait, because shutdown usually happens under a deadline, such as a container being stopped. Step 3 is the forceful part: shutdownNow() interrupts the running tasks, and the list it returns tells us which queued tasks never ran, so we can log them, save them, or at least count them.

Step 4 exists because interrupting is only a request. Well-written tasks notice the interrupt, for example because a blocking call like sleep() or a queue's take() throws InterruptedException, and finish quickly. The second short wait gives them that chance, and if it fails, the log tells us some task is ignoring interrupts.

Step 5 handles the case where the thread doing the shutdown is itself interrupted while waiting. We still stop the pool with shutdownNow(), and then we restore the interrupt flag, because catching InterruptedException clears it. Restoring it lets the code that called us see that an interrupt happened, which is the rule for any code that catches InterruptedException without rethrowing it.

3Writing Tasks That Respond to Interrupts

The method above can only be as graceful as the tasks. A task that runs in a loop should check whether it has been interrupted, and a task that catches InterruptedException should stop rather than carry on.

Java
Runnable exporter = () -> {
while (!Thread.currentThread().isInterrupted()) { // check between units of work
Batch b = nextBatch();
if (b == null) return;
write(b);
}
log.info("export stopped by interrupt"); // printed after shutdownNow()
};

Notice that the check happens between batches, so each batch is either written completely or not started. That makes an interrupted task safe as well as fast to stop.

4What close() Added in Java 19

Since Java 19, ExecutorService extends AutoCloseable and has a default close() method. close() starts an orderly shutdown like shutdown() and then waits until all tasks have completed and the executor has terminated. If the thread calling close() is interrupted while waiting, close() calls shutdownNow() to stop the running tasks, keeps waiting until they finish, and then restores the interrupt flag.

Notice what close() does not have: a timeout. It waits as long as the tasks take. That is right for an executor whose tasks are all part of one operation that we want to finish, but it is not a replacement for the bounded method above when we must stop within a deadline, such as an application shutdown.

5Try-With-Resources for Executors Scoped to One Operation

Because ExecutorService is AutoCloseable, an executor that exists only for one operation fits naturally in try-with-resources. The executor is created, used and closed in one block, and the block cannot end before all its tasks have finished.

Java
List<Report> reports;
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<Report>> futures = customers.stream()
.map(c -> ex.submit(() -> buildReport(c))) // one virtual thread per customer
.toList();
reports = futures.stream().map(Future::resultNow).toList(); // unsafe here: tasks may not be done yet
}
// Better: read the results after the block, when close() has waited for every task
List<Future<Report>> futures;
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
futures = customers.stream().map(c -> ex.submit(() -> buildReport(c))).toList();
} // close(): waits for all reports
List<Report> done = futures.stream().map(Future::resultNow).toList(); // safe: all completed

The first version has a subtle bug: resultNow() throws IllegalStateException if a task has not completed yet, and inside the block it may not have. In the second version, the closing brace waits for every task, so by the time we read the results, all are complete. (resultNow() still throws if a task failed, so real code checks state() or uses get().)

So the rule is simple. For an executor that lives as long as the application, such as a Spring bean, use the bounded shutdown method, or let the framework do it. For an executor that serves one operation, use try-with-resources and let close() wait.

6Follow-up questions

What happens if we never shut down an executor?

Its threads stay alive. Executors.newFixedThreadPool creates non-daemon threads, so the JVM cannot exit normally while they exist, and in application servers or tests the threads leak on every redeploy or test run. Virtual-thread executors do not block JVM exit, but tasks may be cut off when it exits.

Does shutdown() wait for queued tasks to start?

shutdown() itself does not wait for anything; it returns at once. It lets the already queued tasks run in the normal order, and awaitTermination is what waits for them to finish.

What does close() do on ForkJoinPool.commonPool()?

Nothing. The common pool cannot be shut down, so its shutdown(), shutdownNow() and close() have no effect. Only pools we create ourselves can be shut down.

7Conclusion

In this answer, we wrote the standard graceful shutdown: shutdown() to stop accepting and let queued tasks finish, awaitTermination with a timeout, shutdownNow() to interrupt running tasks and collect queued ones if time runs out, a short second wait, and on interruption, shutdownNow() plus restoring the interrupt flag. We also saw that close(), added in Java 19 when ExecutorService became AutoCloseable, shuts down and waits for all tasks without a timeout, which makes try-with-resources ideal for executors scoped to one operation.

What to say in the interviewAbout 90 seconds aloud

Open with

The standard pattern has four steps. First I call shutdown, which stops the executor from accepting new tasks but lets queued and running tasks finish; it returns immediately.

Then, if they want more

Then I call awaitTermination with a timeout, say 30 seconds, because shutdown usually happens under a deadline. If it returns false, I call shutdownNow, which interrupts the running tasks and returns the queued tasks that never started, so I can log or save them.

Then I await again briefly, maybe five seconds, because an interrupt is only a request, and if that fails too I log that some task ignores interrupts.

And the whole thing is in a try block: if my thread is interrupted while waiting, I catch InterruptedException, call shutdownNow, and restore the interrupt flag with Thread.currentThread().interrupt(), since catching it clears the flag. Tasks should cooperate by checking the interrupt flag between units of work. Since Java 19, ExecutorService implements AutoCloseable.

Its close method does an orderly shutdown and then waits until all tasks have completed; if the caller is interrupted while waiting, it calls shutdownNow and keeps waiting. There is no timeout. So for an executor scoped to one operation, like fanning out work on virtual threads, I use try-with-resources, and when the block ends all tasks are done.

For long-lived executors with a deadline, like at application shutdown, I still use the bounded method or let Spring manage it.

About this answer

Last updated
12 November 2026
Versions it names
Java 19
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write the standard code to shut down an ExecutorService gracefully, and explain what...": https://scrivio-interview-library.netlify.app/java/executors/25f8dfbd1b/