Sub topic 8
Shutting Down an ExecutorService Cleanly
In earlier chapters you handed tasks to a thread pool and got results back with Future. One job is left: telling the pool you are finished with it. This chapter shows why that step matters, which methods do it, and the standard pattern most Java programs use.
Why a Pool Must Be Shut Down
An ExecutorService keeps its worker threads alive after a task ends. This is on purpose. Reusing threads is cheaper than creating new ones for every task.
The cost is that those threads stay alive until you tell them to stop. By default, pool threads are non-daemon threads. A non-daemon thread is a thread that keeps the Java Virtual Machine (JVM) running for as long as it is alive. So if you forget to shut the pool down, your main method can reach its last line and the program still will not exit. It just hangs.
Shutting down cleanly has three goals:
- Stop accepting new tasks.
- Let tasks that are already running or waiting get a fair chance to finish.
- Make sure the program ends, even if some task misbehaves.
The Three Shutdown Methods
The ExecutorService interface gives you three methods for this job.
| Method | What it does | Does it wait? |
|---|---|---|
| `shutdown()` | Stops accepting new tasks. Tasks already running and tasks waiting in the queue still run to the end. | No. It returns right away. |
| `awaitTermination(time, unit)` | Blocks the calling thread until all tasks finish or the time runs out. Returns `true` if the pool finished. | Yes, up to the time limit. |
| `shutdownNow()` | Stops accepting new tasks, removes waiting tasks from the queue, and interrupts running tasks. Returns the list of tasks that never started. | No. It returns right away. |
Two helper methods let you check the state:
isShutdown()returnstrueonceshutdown()orshutdownNow()has been called.isTerminated()returnstrueonly when shutdown has been called and every task has finished.
shutdown: the polite request
shutdown() is a polite request. It closes the door to new work but lets the pool finish what it already has. A common beginner mistake is to think shutdown() waits for tasks to end. It does not. It returns at once, and the tasks keep running in the background.
awaitTermination: waiting with a time limit
awaitTermination is how you wait. You give it a maximum time. A time limit is important because a task might loop forever or get stuck waiting on a network call. Without a limit, your program could wait forever too.
awaitTermination throws InterruptedException. That is a checked exception, so you must catch it or declare it. It happens when some other thread interrupts the thread that is waiting.
shutdownNow: the forceful request
shutdownNow() is more forceful, but it is still not a kill switch. It interrupts each running thread. An interrupt is a signal that sets a flag on the thread. Blocking methods such as Thread.sleep notice the flag and throw InterruptedException. A task that never sleeps, waits, or checks the flag will just keep going.
The Lifecycle of a Pool
A pool moves through a small set of states. It can never go back to running once shutdown has started.
In the ShuttingDown state, queued tasks still run. In the Stopping state, the queue has been emptied and running tasks have been interrupted.
The Standard Shutdown Pattern
Most code combines the three methods into one pattern. Here it is in full.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ShutdownDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int i = 0; i < 8; i++) {
int id = i;
pool.submit(() -> System.out.println("Task " + id));
}
pool.shutdown();
try {
if (!pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
} catch (InterruptedException e) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}Here is what each step does:
pool.shutdown()stops new tasks from being accepted. The eight tasks already submitted will still run.pool.awaitTermination(10, TimeUnit.SECONDS)waits up to ten seconds for those tasks to finish.- If the wait returns
false, some tasks are still running after ten seconds. The code callsshutdownNow()to interrupt them. - If the main thread is itself interrupted while waiting, the
catchblock runs. It forces the pool to stop. Then it callsThread.currentThread().interrupt().
That last line needs a closer look. When InterruptedException is thrown, Java clears the thread's interrupt flag. If you just swallowed the exception, any code higher up would never learn that someone asked this thread to stop. Calling interrupt() again sets the flag back so the signal is not lost. This is called restoring the interrupt status.
Seeing shutdownNow in Action
The next program shows what shutdownNow() really does. It starts five slow tasks on a pool of two threads. Only two tasks can run at once, so three wait in the queue.
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ShutdownNowDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 5; i++) {
int id = i;
pool.submit(() -> {
try {
Thread.sleep(5000);
System.out.println("Task " + id + " finished");
} catch (InterruptedException e) {
System.out.println("Task " + id + " was interrupted");
}
});
}
Thread.sleep(500);
List<Runnable> neverStarted = pool.shutdownNow();
System.out.println("Tasks that never started: " + neverStarted.size());
boolean done = pool.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("Terminated: " + done);
}
}A typical run prints this. The first three lines can appear in a different order:
Tasks that never started: 3
Task 0 was interrupted
Task 1 was interrupted
Terminated: trueTasks 0 and 1 were sleeping, so the interrupt woke them with an InterruptedException. Tasks 2, 3, and 4 never started. shutdownNow() handed them back in a list. You could log them or save them to run later.
The program ends quickly, after about half a second instead of fifteen seconds. That only works because Thread.sleep responds to interrupts.
Submitting After Shutdown
Once a pool is shut down, it refuses new work. Calling submit or execute throws a RejectedExecutionException. This is an unchecked exception, which means the compiler does not force you to catch it.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
public class RejectAfterShutdown {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.shutdown();
try {
pool.submit(() -> System.out.println("Too late"));
} catch (RejectedExecutionException e) {
System.out.println("Rejected: the pool is shut down");
}
System.out.println("isShutdown = " + pool.isShutdown());
System.out.println("isTerminated = " + pool.isTerminated());
}
}This prints Rejected: the pool is shut down, then isShutdown = true. The last line usually prints isTerminated = true, because the pool had no tasks left to finish. If you see false, the worker thread simply had not finished exiting yet. That is why your code should wait with awaitTermination instead of checking isTerminated() once.
Common Mistakes and Edge Cases
- Forgetting shutdown entirely. The program hangs at the end. Put the shutdown in a
finallyblock so it runs even if an exception is thrown, as theFutureexamples in earlier chapters did. - Thinking
shutdown()waits. It does not. CallawaitTerminationif you need the results to be done before you go on. - Waiting with no limit. A stuck task can freeze your program forever. Always pass a sensible timeout.
- Swallowing
InterruptedException. Restore the flag withThread.currentThread().interrupt(). - Tasks that ignore interrupts. A loop such as
while (true) { count++; }will keep running aftershutdownNow(). Write loops likewhile (!Thread.currentThread().isInterrupted())instead. - Calling shutdown twice. This is harmless. A second call to
shutdown()does nothing extra.
Exercises
Exercise
A program submits three tasks, calls pool.shutdown(), and then immediately prints "All done". The tasks each take two seconds. Will "All done" appear before or after the tasks finish, and why?
Show answer
Before. shutdown() only stops new tasks from being accepted and returns right away. It does not wait. To print "All done" after the tasks finish, call pool.awaitTermination with a timeout before printing.
Exercise
A task runs the loop while (true) { total++; } with no sleep or other blocking call. The main thread calls shutdownNow() and then awaitTermination(2, TimeUnit.SECONDS). What does awaitTermination return, and how could you fix the task?
Show answer
It returns false, because the loop never checks the interrupt flag and keeps running. Change the loop condition to while (!Thread.currentThread().isInterrupted()) so the task stops when shutdownNow() interrupts it.
Exercise
In the standard shutdown pattern, why does the catch block call Thread.currentThread().interrupt() after catching InterruptedException?
Show answer
When InterruptedException is thrown, Java clears the thread's interrupt flag. Calling interrupt() sets the flag again so code higher up the call stack can still see that the thread was asked to stop.