Search code examples
javamultithreadinginterrupt

I want my thread to handle interruption, but I can't catch InterruptedException because it is a checked exception


I have a thread in Java which calls

t.interrupt();

making t (a different thread) be interrupted. I want the "t" thread to then catch an InterruptedException but Eclipse won't let me put an InterruptedException in saying it's not thrown in the try body. How can I get the InterruptedException to be called? Am I using t.interrupt() wrong?


Solution

  • While the other answers are correct, a fuller explanation is appropriate.

    A thread can be safely interrupted (in the general sense of the word) only at specific points in its execution. In particular, it can be interrupted safely when it has issued a wait() call, or has invoked a service that can issue wait(). This is why InterruptedException is a checked exception and not a runtime (unchecked) exception. Allowing a thread to be arbitrarily interrupted at any point would make execution non-deterministic (at least that's the way the JVM was specified). There is a Thread#stop() method which is strongly deprecated because it causes more problems than it solves. From the Javadoc

    This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.

    If you need to interrupt a running thread, then you must periodically poll the interrupted status with Thread.interrupted() or .isInterrupted() or poll a shared variable, and take appropriate action yourself.

    Note: The term "interrupted" above (except as part of a method name) is intended in the general sense, not the specific meaning of calling Thread#interrupt().