Video in progress
Why is it a mistake to catch InterruptedException and leave the catch block empty?
When the exception is thrown, the interrupt flag is cleared. If you swallow it, the code above and the executor never find out that a stop was requested, and as a result the service doesn't shut down or the task isn't cancelled.
📖 Answer
A very common piece of code:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// nothing
}
Someone called shutdownNow(), the thread woke up, but the loop keeps going. The app hangs for 30 seconds during a deploy, and then Kubernetes kills it with SIGKILL.
There are two correct options:
// 1. If you can, pass it up
void waitForSlot() throws InterruptedException {
Thread.sleep(1000);
}
// 2. If the signature doesn't allow it, restore the flag and exit
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
You can also wrap it in a RuntimeException, but call interrupt() first.
Sonar and IntelliJ flag this case with a warning. In code review this is the first thing I look at: one extra line, but it keeps graceful shutdown working.
Sign up to mark studied questions and save your progress.