Sub topic 8
Shutting Down an ExecutorService Cleanly
An ExecutorService keeps its worker threads alive after the tasks finish. It does this so it can reuse them for the next task. That is useful while your program runs. It becomes a problem when the program should end.
Why Shutdown Matters
A pool from Executors.newFixedThreadPool makes ordinary threads, not daemon threads. A daemon thread is a background thread that does not stop the Java Virtual Machine (JVM) from exiting. Ordinary threads do stop it. So if you never shut the pool down, its idle threads sit waiting for work and your program never ends.
Shutting down tells the pool that no more work is coming, so it can finish and release its threads.
The Three Shutdown Methods
| Method | What it does | Does it wait? |
|---|---|---|
| `shutdown()` | Stops accepting new tasks. Tasks already submitted still run. | No, it returns at once |
| `awaitTermination(time, unit)` | Blocks until all tasks finish or the time runs out. Returns `true` if the pool finished. | Yes, up to the limit |
| `shutdownNow()` | Interrupts running tasks and removes waiting tasks from the queue. Returns the list of tasks that never started. | No |
Each method only does part of the job, so you usually use them together.
How the Pool Moves Between States
After shutdown(), any new submit call fails with a RejectedExecutionException. That exception means the pool refused the task.
The Standard Shutdown Pattern
This pattern works in most programs:
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()closes the door to new tasks. The 8 tasks already submitted keep running.awaitTermination(10, TimeUnit.SECONDS)waits up to 10 seconds for them to finish.- If the wait returns
false, some tasks are stuck, soshutdownNow()interrupts them. - If the main thread gets interrupted while waiting, the
catchblock forces the shutdown. It then callsThread.currentThread().interrupt()to set the interrupt flag again.
The interrupt flag is a yes/no marker on a thread that says "someone asked you to stop." When Java throws InterruptedException, it clears that flag. Setting it again lets code higher up still see the request.
Common Mistakes
- Forgetting to shut down. The program hangs after
mainends. - Calling only
shutdown()and then reading results.shutdown()does not wait. UseawaitTerminationorFuture.getif you need the work to be done. - Swallowing
InterruptedException. An emptycatchblock hides the stop request. Restore the flag instead. - Submitting after shutdown. This throws
RejectedExecutionException.
Exercise
You call pool.shutdown() and then immediately print "All done". Some tasks are still printing after your message appears. Why, and how do you fix it?
Show answer
shutdown() only stops new tasks from being accepted. It returns right away without waiting. Call pool.awaitTermination with a time limit after shutdown() and print "All done" only after it returns true.
Exercise
What does awaitTermination return if the time limit passes before all tasks finish, and what should you usually do next?
Show answer
It returns false. You usually call shutdownNow() next to interrupt the tasks that are still running and drop the ones still waiting in the queue.