SteelReed

Search

Search posts, questions…

ConcurrencyQuestion 3 / 19

Middle

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.

yesnoAnother thread callsinterruptInterrupt flag setBlocking method throwsInterruptedException,clears flagCan you rethrow?Declare throwsinterrupt againthen stop work

3 points to say:

  1. Interrupt is a request to stop, not a kill: the thread checks and stops on its own.
  2. Catching InterruptedException means the flag is cleared: rethrow, or call Thread.currentThread().interrupt() and stop; never swallow it in an empty catch.
  3. 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.