Why Invoke Thread.Currentthread.Interrupt() in a Catch Interruptexception Block

Why invoke Thread.currentThread.interrupt() in a catch InterruptException block?

This is done to keep state.

When you catch the InterruptedException and swallow it, you essentially prevent any higher-level methods/thread groups from noticing the interrupt. Which may cause problems.

By calling Thread.currentThread().interrupt(), you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.

Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:

Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.

Should I Thread.currentThread.interrupt() before I throw an exception back?

Yes, you should call interrupt() to let the calling code know that the thread has been interrupted. If you don't do it, since the InterruptedException clears it, the calling code will have no way to know about the interruption and won't stop running although it should.

Let me quote Java Concurrency in Practice:

Restore the interrupt. Sometimes you cannot throw InterruptedException, for instance when your code is part of a Runnable. In these situations, you must catch InterruptedException and restore the interrupted status by calling interrupt on the current thread, so that code higher up the call stack can see that an interrupt was issued,
as demonstrated in Listing 5.10.

public class TaskRunnable implements Runnable {
BlockingQueue<Task> queue;
...
public void run() {
try {
processTask(queue.take());
} catch (InterruptedException e) {
// restore interrupted status
Thread.currentThread().interrupt();
}
}
}

Why would you catch InterruptedException to call Thread.currentThread.interrupt()?

The simple answer is that InterruptedException is a checked exception and it is not in the signature of the Runnable.run method (or the Executable.execute() method). So you have to catch it. And once you've caught it, calling Thread.interrupt() to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.

Why Thread.currentThread().interrupt() be called?

When you catch an InterruptedException, the thread's interrupted flag is cleared. By calling Thread.currentThread().interrupt(), you set the interrupted flag again so clients higher up the stack know the thread has been interrupted and can react accordingly. In the example, the Executor is one such client.

You may want to read this article for a more thorough explanation.



Related Topics



Leave a reply



Submit