Junior
What is the InterruptedException exception?
sobes.tech AI
Answer from AI
InterruptedException is a checked exception in Java that is thrown when a thread is waiting, sleeping, or otherwise occupied, and that activity is interrupted by another thread.
Main points:
- It inherits from
Exception. - It indicates that a thread that was blocked (for example, in
wait(),sleep(),join(), or blocking I/O operations) has received an interrupt request. - When this exception is thrown, the thread clears the interrupt flag.
Example handling:
// Example of handling InterruptedException
public class InterruptedTask implements Runnable {
@Override
public void run() {
try {
// The thread performs some work that can be interrupted
Thread.sleep(5000); // Example of a blocking operation
System.out.println("Task completed without interruption.");
} catch (InterruptedException e) {
// An interruption was received
System.out.println("Task was interrupted.");
// You can re-set the interrupt flag so that
// higher-level code knows about the interruption
Thread.currentThread().interrupt();
// Additional logic for exit or resource cleanup
}
}
public static void main(String[] args) {
Thread worker = new Thread(new InterruptedTask());
worker.start();
try {
// Wait a bit, then interrupt the thread
Thread.sleep(1000);
worker.interrupt(); // Interrupt the thread
} catch (InterruptedException e) {
e.printStackTrace(); // Handling exception in main thread
}
}
}
Proper handling of InterruptedException is important for creating reliable multithreaded applications. Typical strategies:
- Propagate the exception further (
throw new InterruptedException();). - Re-set the interrupt flag (
Thread.currentThread().interrupt();) and possibly terminate execution. - Catch the exception, perform cleanup, and terminate the thread.