我们在捕获到InterruptedException后,真的应该中断当前线程吗?

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

Should we really interrupt the current thread after catching InterruptedException?

问题

我有一段代码,由于旧代码我不能进行太多更改,所以其中一部分需要等待一段时间作为繁忙等待的一部分。我已经阅读了为什么应该这样做的理由,可以在这里找到1和[2],并且它被提出为一个不费吹灰之力的经验法则。始终要这样做。如果我理解正确,这被认为是必要的,因为调用堆栈中更高层的一些代码可能正在执行诸如:

while (!Thread.currentThread().isInterrupted()) {

而且如果没有调用

Thread.currentThread().interrupt()

或者重新抛出它,就会失败。

现在回到我的情况。我调用了微小的sleep方法。如果我在繁忙等待的过程中被唤醒,我不在乎,如果需要的话我会再次休眠。如果实际上有一段关心线程中断标志的代码,我绝对不希望它触发,因为我不想停止这个操作,在这种情况下,不带重试且不设置标志的吞下似乎是正确的操作,然而我没有看到任何提到,在某些情况下吞下可以是正确的反应。

英文:

I have code, which needs to wait a while as a part of busy-wait (due to legacy code I cannot change that much). I've read the reasoning why I should do that here 1 and [2], and it's presented as no-brainer rule of thumb. Do this always. IIUC it's sold as necessary because some code higher up call stack can be doing things like:

while (!Thread.currentThread().isInterrupted()) {

and without calling

Thread.currentThread().interrupt()

or rethrowing it would fail.

Now back to my case. I called minuscule method sleep. If I was woken up in the middle of busy wait, I don't care, I will sleep again if I have to. If there actually is a code interested in thread interrupted flag, I definitely don't want it to kick in, because I don't want to halt this operation, and in this case, swallowing without retry and without setting flag seems to be correct operation, however I did not see any mention, that swallow can be correct reaction in some situation.

答案1

得分: 1

在Java并发方面有一本很好的书:《Java并发实践》。在第7章第7.1.3节中有这样的内容:

> 只有实现线程中断策略的代码才可以忽略中断请求。通用任务和库代码不应该忽略中断请求。

因此,在某些情况下是可以忽略中断的。

英文:

There is a good book on concurrency in Java: Java Concurrency in Practice. In chapter 7, section 7.1.3 there is this text:

> 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.

So, it is possible to swallow the interrupt in some situations.

huangapple
  • 本文由 发表于 2020年3月15日 19:56:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/60692593.html
匿名

发表评论

匿名网友

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

确定