How should you handle InterruptedException correctly?
Short answer
Interrupt is cooperative cancellation: one thread sets a flag, the other decides for itself to stop. When you catch InterruptedException the flag has already been cleared, so you must rethrow it or restore the flag and stop.
3 points to say:
- Interrupt is a request to stop, not a kill: the thread checks and stops on its own.
- Catching
InterruptedExceptionmeans the flag is cleared: rethrow, or callThread.currentThread().interrupt()and stop; never swallow it in an empty catch. - A compute loop that calls no blocking method must check
isInterrupted()itself.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.