Interrupting Long-Running Loops
What you'll learn: How to make long-running loops responsive to thread interruption by explicitly checking the interrupt status.
The Problem with Busy Loops
You've learned that Thread.interrupt() immediately wakes up threads blocked on sleep or other blocking operations. But what about threads stuck in a busy loop—one that performs computations or operations without ever calling a blocking method? These threads won't automatically respond to interruption because they never enter a state where InterruptedException is thrown.
The Solution: Explicit Checks
To make a busy loop interruptible, you must explicitly check the thread's interruption status inside the loop. Use Thread.currentThread().isInterrupted() as part of your loop condition or within the loop body.
Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
// Perform computation or work
processNextItem();
}
System.out.println("Loop interrupted, cleaning up...");
};
Thread worker = new Thread(task);
worker.start();
// Later, from another thread:
worker.interrupt(); // Signals the loop to stop
Why This Matters
Without explicit checks, a thread running an infinite loop has no way to gracefully exit when interrupted. The interrupt flag is set, but nothing observes it. By checking isInterrupted() in your loop condition, you create a cooperative cancellation point where your thread can detect the signal and respond appropriately.
Think of it like checking your phone during a long drive: if you never look, you'll miss important messages. The interruption is the message, and checking isInterrupted() is looking at your phone.
Key Takeaway: Always check Thread.currentThread().isInterrupted() in long-running loops that don't call blocking methods, enabling your threads to respond gracefully to interruption requests.