Threads and lifecycle question 4 of 180 mid
Why is swallowing InterruptedException a bug, and what is the correct handling?
- It is not a bug, the exception is informational
- Correct: Catching it clears the flag, so the layers above lose the only signal that cancellation was requested
- You must always call
Thread.stop()afterwards - You must rethrow it as a
RuntimeException
Throwing InterruptedException clears the interrupt flag. If you catch it and log, the request to
cancel has now been destroyed: the loop above you keeps going, the pool's shutdownNow appears to do
nothing, and the JVM will not exit.
Two correct endings. Propagate it, if your signature allows, and let the caller decide. Or, if you cannot, restore the flag before returning:
try {
task = queue.take();
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // the next blocking call will see it
return; // and stop doing work
}
Restoring without also stopping the work is the half-fix that still loses the cancellation.