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

3

12

In Effective Java (page 275), there is this code segment:

...
for (int i = 0; i < concurrency; i++) {
  executor.execute(new Runnable() {
    public void run() {
    ready.countDown();
    try {
      start.await();
      action.run();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      done.countDown();
    }
  }
}
...

What's the use of catching the interrupted exception just to re-raise it? Why not just let it fly?

Rea answered 13/12, 2009 at 7:56 Comment(0)
M
16

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.

Micky answered 13/12, 2009 at 8:16 Comment(3)
Assuming you want the thread to be actually interrupted. You can just catch and swallow the exception as well which will suppress the thread interruption.Locomotion
You mean it's not in the signature of Runnable. I'd use a Callable instead. Also - calling Thread.currentThread().interrupt() will not throw that exception? So what's the point in throwing it?Rea
I believe you mean that the InterruptedException is a checked exception and is not in the signature of Runnable.run() (not Executor.execute).Lambskin
B
0

Sometimes you can't ignore exception and you must catch it. Mainly this happens when you override method which can't throw InterruptedException in accordance with its signature. For example, this approach is usually used in Runnable.run() method.

Bergmann answered 13/12, 2009 at 8:20 Comment(0)
H
0

The executor can interrupt tasks if they are cancelled but it clears the interrupted flag between tasks to avoid one cancelled task interrupting an unrelated task.

As such, interrupting the current thread here would be dangerous if it actually did anything.

A simpler way around this is to use Callable or ignore the interrupt.

Additionally it is a good idea to catch and log any error or exception thrown in the try/catch block otherwise the exception/error will be discarded and your program could be failing but you won't know it is or why.

Hedley answered 13/12, 2009 at 15:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.