Java Concurrency Interview

Threads and lifecycle question 4 of 180 mid

Why is swallowing InterruptedException a bug, and what is the correct handling?

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.

interruption antipattern

Quiz yourself on Threads and lifecycle Suggest a correction