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

半腔热情 提交于 2019-12-29 04:20:46

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1895881/why-would-you-catch-interruptedexception-to-call-thread-currentthread-interrupt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!