In this post, we'll learn what is InterruptedException, common causes, practical examples, how to handle it, and best practices.
What is InterruptedException?
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.
InterruptedException Class Diagram
Why and When to Interrupt Threads?
Resource Reclaiming: If a thread is no longer needed or is stuck, it can be interrupted to reclaim resources.
Task Cancellation: If a particular task carried out by a thread is no longer required.
Shutdown Signal: Often used to signal threads to shut down gracefully in scenarios like application termination.
Practical Example
Let's go through a scenario where we have a thread that sleeps for a long time and we want to interrupt it.
public class InterruptedExceptionExample {
public static void main(String[] args) {
Thread longSleepingThread = new Thread(() -> {
try {
// Simulating a long task with sleep
System.out.println("Going to sleep...");
Thread.sleep(10000); // Sleep for 10 seconds
System.out.println("Woke up normally!");
} catch (InterruptedException e) {
e.printStackTrace();
System.err.println("I was rudely interrupted while sleeping!");
}
});
longSleepingThread.start();
// Main thread will sleep for 2 seconds and then interrupt the longSleepingThread
try {
Thread.sleep(2000);
} catch (InterruptedException ignored) { }
longSleepingThread.interrupt();
}
}
Output:
Going to sleep...
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.InterruptedExceptionExample.lambda$main$0(InterruptedExceptionExample.java:9)
at java.base/java.lang.Thread.run(Thread.java:1623)
I was rudely interrupted while sleeping!
In the above example, the longSleepingThread is supposed to sleep for 10 seconds. However, after only 2 seconds, the main thread interrupts it.
Handling InterruptedException
Catch and Terminate: Once interrupted, the thread should typically terminate its operation.
Restore the Interrupt: If you cannot terminate the thread, then at least restore its interrupted status using Thread.currentThread().interrupt(); to ensure the downstream code recognizes the interrupt.
Avoid Ignoring: Don't swallow the InterruptedException silently. Either handle it or propagate it.
Best Practices
- Always be cautious about interrupting threads, as it can potentially leave shared data in an inconsistent state.
- If a thread is interrupted, ensure that resources it holds, like locks or open files, are released.
- Use the interruption mechanism judiciously, especially when dealing with libraries or frameworks that might not expect it.
Conclusion
Multithreading can be tricky, but understanding mechanisms like the InterruptedException goes a long way in mastering concurrency in Java. Remember, every thread has a purpose, and gracefully handling its life cycle is paramount for robust and scalable applications.
Comments
Post a Comment
Leave Comment