Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
How do you handle thread interruption in Java?
Interruption is a cooperative signal, not a forced stop. Calling thread.interrupt() sets an internal interrupt flag on that thread; it's up to the target thread's code to check for and respond to it.
If the thread is currently blocked in an interruptible method like sleep(), wait(), or join(), that method throws InterruptedException immediately and clears the flag. If the thread is running ordinary CPU-bound code, it must periodically check Thread.currentThread().isInterrupted() itself.
public void run() { while (!Thread.currentThread().isInterrupted()) { try { doWork(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // restore the flag return; // exit cleanly } } }
The common mistake is swallowing InterruptedException silently. Best practice is to either handle it and return or stop the task, or re-set the interrupt flag with Thread.currentThread().interrupt() so calling code further up can also notice and react to it.
More Related questions...