开发者

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

开发者 https://www.devze.com 2022-12-14 08:55 出处:网络
In Effective Java (page 275), there is this code segment: ... for (int i = 0; i < concurrency; i++开发者_StackOverflow中文版) {

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

...
for (int i = 0; i < concurrency; i++开发者_StackOverflow中文版) {
  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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号