The InterruptedException is a checked exception thrown when a thread that's sleeping, waiting, or occupied with a prolonged operation is interrupted. The very purpose of this exception is to indicate that the current thread should stop what it's doing and handle the interruption, usually by terminating.
Common Scenario
Consider a thread sleeping for a certain period:
public class SleepyThread extends Thread {
@Override
public void run() {
try {
Thread.sleep(10000); // Sleep for 10 seconds
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Thread was interrupted!");
}
}
public static void main(String[] args) {
SleepyThread sleepy = new SleepyThread();
sleepy.start();
try {
Thread.sleep(2000); // Main thread sleeps for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
sleepy.interrupt(); // Main thread interrupts the sleepy thread
}
}
Output:
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep0(Native Method)
at java.base/java.lang.Thread.sleep(Thread.java:484)
at com.javaguides.net.SleepyThread.run(SleepyThread.java:7)
Thread was interrupted!
How to Handle InterruptedException
1. Re-throw the Exception:
If you're not sure about how to handle the interruption, propagate the exception:
public void myMethod() throws InterruptedException {
// ... some code
Thread.sleep(1000);
// ... some code
}
2. Restore the Interrupt:
If you catch the InterruptedException but don't want to handle it, reset the interrupt status so that other parts of the program can handle it later:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Set the interrupt flag
}
3. Terminate the Operation:
Use the interruption as a signal to gracefully terminate the thread:
try {
while (!Thread.currentThread().isInterrupted()) {
// ... thread's regular operations
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// Clean up resources, if any
return;
}
Best Practices
Don't just catch the exception and do nothing or print a message. Either propagate it, handle it, or reset the interrupt status.
Instead of using deprecated methods like stop(), use interrupt() and handle the InterruptedException gracefully.
Always check the interrupt status of the thread: Especially in loops or long-running operations, regularly check the interrupt status using Thread.currentThread().isInterrupted() to allow early exits.
Comments
Post a Comment
Leave Comment