beginnerFoundations

How does calling interrupt() on a thread work, and how should InterruptedException be handled correctly?

Calling interrupt() simply sets a boolean interrupt flag on the target thread -- it does not forcibly stop the thread or unwind its stack. If the target thread happens to be blocked inside sleep(), wait(), or join() at the time, those methods immediately throw an InterruptedException and clear the interrupt flag as part of throwing it. There are two correct ways to handle that exception: you can propagate it by declaring throws InterruptedException on your own method and letting the caller decide what to do, or you can catch it, call Thread.currentThread().interrupt() to restore the interrupt flag, and then return or break out of whatever loop you were in. What you should never do is swallow it with an empty catch block, because that silently discards the cancellation signal and prevents the application from shutting down cleanly.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What is an intrinsic lock (monitor) in Java?← Back to all Java Concurrency & Multithreading questions