Swallow InterruptedException in ExecutorService or not?

huangapple go评论61阅读模式
英文:

Swallow InterruptedException in ExecutorService or not?

问题

以下是翻译好的部分:

有一篇IBM的文章。
https://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-#2.1

这篇文章指出不应该忽略 "InterruptedException"。Sonar 中也有相同的建议。

但是在StackOverflow上有一个关于ExecutorService内的InterruptedException的问题,该问题建议我们不应再次设置中断。
https://stackoverflow.com/questions/36364224/interruptedexception-inside-executorservice

IBM的文章可能相当旧,没有考虑现代的Java Concurrent包?
我们应该如何处理ExecutorService中的InterruptedException?

英文:

There is an article by IBM.
https://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-#2.1

This says never swallow interruptedException. The same thing is there on sonar.

"InterruptedException" should not be ignored.

But there is a question on StackOverflow regarding interruptedException inside Executorservice, which suggests, we should not set the interrupt again.
https://stackoverflow.com/questions/36364224/interruptedexception-inside-executorservice

Is the IBM article is quite old, and does not take the modern Java Concurrent package into account?
How should we handle interruptedException in ExecutorService?

答案1

得分: 2

你应该在所有捕获到InterruptedException的地方做出决策,因为它取决于情况和代码的重要性。

一个明智的响应是让你的任务注意到中断,以允许当前线程或在执行器中运行的Runnable进行优雅的取消或关闭。在一个Runnable的最外层部分重置Thread.currentThread().interrupt()可能没有太多意义(因为线程会在之后立即退出,或者执行器正在管理那个中断)。

但是,如果你在任务控制的几层调用栈下捕获了这个异常,那么重置Thread.currentThread().interrupt()可能有助于任务的高层级看到并优雅地退出 - 但前提是它们在每个阶段都检查Thread.currentThread().isInterrupted(),或者你的代码传递InterruptedException或应用程序特定的异常。

英文:

You should make a decision in all places you have trapped InterruptedException as it depends on the situation and importance for your code.

A sensible response is for your task is to take heed of the interrupt, to allow a graceful cancellation or shutdown of the current thread or Runnable within executor. There won't much point resetting Thread.currentThread().interrupt() in your outermost part of a Runnable (as thread will exit just afterwards, or Executor is managing that interrupt).

However if you are trapping that exception several layers of call stack below the task control then resetting Thread.currentThread().interrupt() may help the higher levels of your task see and bail out gracefully - but only if they are checking Thread.currentThread().isInterrupted() at each stage or your code passes on the InterruptedException or an application specific exception.

huangapple
  • 本文由 发表于 2020年7月28日 14:27:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63128208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定