Common Interruption Anti-Patterns
What you'll learn: The typical mistakes developers make when handling thread interruption that can break cancellation mechanisms.
After learning the proper ways to handle interruption, it's crucial to recognize the common pitfalls that undermine Java's cooperative cancellation model.
Anti-Pattern 1: Swallowing InterruptedException
The worst offense is catching InterruptedException and doing nothing:
// WRONG: Silent swallowing
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Empty catch block - interruption signal lost!
}
This is like ignoring a fire alarm. The interruption was meant to signal cancellation, but you've destroyed the evidence. The thread continues as if nothing happened, and calling code has no way to know the interruption occurred.
Anti-Pattern 2: Logging Without Restoring Status
Slightly better, but still broken:
// WRONG: Logs but loses interrupt status
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted"); // Awareness without action
}
You acknowledge the interruption, but fail to preserve it. Any code higher up the call stack that checks Thread.interrupted() or isInterrupted() will see false.
Anti-Pattern 3: Ignoring Interrupt Status in Loops
// WRONG: Loop ignores interruption
while (!finished) {
doWork(); // Never checks Thread.currentThread().isInterrupted()
}
If doWork() doesn't throw InterruptedException, your loop becomes uninterruptible.
The Correct Response
Always restore the interrupt status:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore the flag
// Then handle appropriately (return, throw, etc.)
}
Key Takeaway: Never swallow InterruptedException silently—always restore the interrupt status with Thread.currentThread().interrupt() so higher-level code can respond to cancellation requests properly.