Video in progress
What should you do when you catch InterruptedException, and what does swallowing it lead to?
Either you pass the exception up, or you put the interrupt flag back with Thread.currentThread().interrupt(). If you swallow it, the stop request is lost and the executor shutdown hangs.
📖 Answer
When an InterruptedException is thrown, the JVM clears the thread's interrupt flag. If you just log it and carry on, the code above you never sees the "someone asked me to stop" signal again.
Wrong:
try {
queue.take();
} catch (InterruptedException e) {
log.warn("interrupted"); // the flag is gone
}
The right options:
// 1) keep throws InterruptedException in the method signature: the cleanest way
// 2) if you can't pass the checked exception on
catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the flag
throw new IllegalStateException("to'xtatildi", e);
}
In prod it looks like this: executor.shutdownNow() is called, but the application waits until the awaitTermination timeout, and Kubernetes kills the pod with SIGKILL. In a thread dump, the worker threads are still sitting in take() or sleep().
The same rule applies when you wrap an exception: always pass the cause to the new exception (new X("...", e)), otherwise the original stack trace is lost.
Sign up to mark studied questions and save your progress.