Java InterruptedException
A thread waiting in an interruptible operation can receive InterruptedException. A handler that cannot propagate it can restore the interrupt status and return.
A simple example
InterruptedException
- Start with A thread is waiting
- Do this Interrupt the wait
- Result Interrupted wait
Syntax
Thread.sleep(milliseconds)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaStop waiting when a shift ends
A dispatch worker is about to wait for another pickup. A shutdown request interrupts the worker, so it should stop waiting and preserve the signal for the code responsible for ending the shift.
class Main {
public static void main(String[] args) throws Exception {
Thread.currentThread().interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException stop) {
Thread.currentThread().interrupt();
System.out.println("Shift ended");
return;
}
}
}
Shift ended
The example sets the interrupt flag before sleep, so the wait ends immediately. The handler restores the flag before leaving the worker.
Check that a worker passes on shutdown
A print worker stops waiting as its shift ends. The queue supervisor reads the interrupt flag afterward to decide whether it should schedule another job on that thread.
class Main {
public static void main(String[] args) throws Exception {
var worker = Thread.currentThread();
worker.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException stop) {
worker.interrupt();
}
if (worker.isInterrupted()) System.out.println("Shutdown requested");
}
}
Shutdown requested
isInterrupted observes the restored flag without clearing it.
Handle the end of a scanning shift
The supervisor signals the scanning worker just before it waits. Observe the interrupt signal in a worker, restore it after handling an interrupted wait, and report whether a shutdown was requested.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
Thread.currentThread().interrupt();
try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
System.out.println(Thread.interrupted());
}
}
true
What to watch for
The interrupted wait clears the status. Restore it with Thread.currentThread().interrupt() when callers need to see the shutdown request.