Interruption Clears the Status
You'll learn: Why catching an InterruptedException automatically resets the thread's interrupted flag to false.
The Automatic Reset
When a thread is interrupted while blocked (in sleep(), wait(), or similar), it throws an InterruptedException. Here's the critical detail: the act of throwing this exception automatically clears the interrupted status. After you catch the exception, calling isInterrupted() will return false, even though an interruption just occurred.
Why This Matters
This behavior can be surprising. You might expect the interrupted flag to remain set after catching the exception, but Java clears it as part of throwing InterruptedException. This means if you simply catch and ignore the exception, all evidence of the interruption vanishes:
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Flag is now CLEAR - interruption evidence is gone!
}
// Thread.currentThread().isInterrupted() returns false here
The Right Response
This is why you learned to restore the interrupt status in catch blocks. Since the exception-throwing process clears the flag, you should explicitly restore it if you're not ready to fully handle the interruption:
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore the flag
// Now other code can see this thread was interrupted
}
Think of It Like This
Imagine a fire alarm that resets itself the moment firefighters arrive. The alarm notified them (threw the exception), but now there's no evidence for the next shift. Unless the firefighters leave a note (restore the status), the next team won't know there was ever a problem.
Key Takeaway: Catching InterruptedException automatically clears the interrupted flag; restore it with Thread.currentThread().interrupt() if you're not handling the interruption completely.