Patterns and antipatterns question 157 of 180 mid
What is the two-phase termination pattern?
- Calling
stop()twice - Correct: Signalling a thread to finish (a flag plus an interrupt), then letting it do its own cleanup before it exits
- Shutting down two pools in order
- A GC phase
The pattern separates "please stop" from "has stopped". The requester sets a volatile flag and
interrupts the worker, so both a busy worker and a blocked one notice. The worker checks the flag at
safe points, catches InterruptedException as a stop signal, and then runs its own shutdown: flush
buffers, release resources, notify a latch.
void shutdown() {
running = false; // volatile
worker.interrupt(); // wake it if it is blocked
}
Why both: the flag alone leaves a blocked thread asleep, and the interrupt alone can be missed if it
arrives between a check and a blocking call. The termination is complete only when the worker says so,
which is what the join or the latch is for.
Quiz yourself on Patterns and antipatterns Suggest a correction