InterruptedException: Thread Interruption
What you'll learn: How InterruptedException signals that a thread's blocking operation was interrupted and why proper handling matters.
What Is InterruptedException?
InterruptedException is a checked exception thrown when a thread is waiting, sleeping, or otherwise blocked, and another thread interrupts it. This is Java's cooperative mechanism for one thread to signal another that it should stop what it's doing.
Think of it like tapping someone on the shoulder while they're napping. They wake up suddenly and need to decide whether to go back to sleep or get up and do something else.
When Does It Occur?
InterruptedException is most commonly thrown by:
Thread.sleep(milliseconds)— when a sleeping thread is interrupted- Blocking I/O operations
- Waiting on locks or conditions
- Other thread coordination methods
Why It's Checked
Unlike RuntimeException, InterruptedException is checked because interruption is an expected event in concurrent programs. The compiler forces you to acknowledge that your thread might be interrupted and handle it appropriately.
Handling InterruptedException
When you catch InterruptedException, you typically have two options:
- Propagate it — declare
throws InterruptedExceptionin your method signature - Handle and restore interrupt status — if you can't throw it, call
Thread.currentThread().interrupt()to preserve the interruption signal for code higher up
Ignoring or swallowing InterruptedException without restoring the interrupt status is a common mistake that breaks thread cancellation mechanisms.
The Pattern
When your code sleeps or blocks, you must handle the interruption:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Option 1: Propagate (if method declares throws)
// Option 2: Restore and handle
Thread.currentThread().interrupt();
// Clean up and exit
}
Key Takeaway: InterruptedException signals cooperative thread cancellation during blocking operations and must be handled properly—either by propagating it or restoring the thread's interrupt status.