Search code examples
javamultithreadinginterruption

Thread Interruption in java


I want some clarification on thread interruption.

What if a thread goes a long time without invoking a method that throws anInterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:

for (int i = 0; i < inputs.length; i++) {
    heavyCrunch(inputs[i]);
    if (Thread.interrupted()) {
        // We've been interrupted: no more crunching.
        return;
    }
}

When I call the method Thread.interrupt() it throws interrupted exception so, why I need to do if (Thread.interrupted()) I will simply do that

try {
    for (int i = 0; i < inputs.length; i++) {
        heavyCrunch(inputs[i]);
        if (Thread.interrupted()) {
            // We've been interrupted: no more crunching.
            return;
        }
    }
} catch (InterruptedException ex) {
        ...
}

Solution

  • When you call Thread.interrupt() on another thread, two things happen:

    1. That thread's interrupt flag is set.
    2. If the thread is blocked in a method that throws InterruptedException, that method will throw an exception immediately.

    If the thread is busy in some code that does not throw InterruptedException, you won't get any exception. That's why you'd need to check if (Thread.interrupted()), to check the flag.

    In your sample code the Java compiler would complain about an invalid catch block because none of the code in the try block throws InterruptedException.