简体   繁体   English

spurios唤醒是否伴随InterruptedException?

[英]Are spurios wakeups accompanied by an InterruptedException?

The javadoc for Object.wait mentions, Object.wait的Javadoc提到,

As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop. 与一个参数版本一样,可能会产生中断和虚假唤醒,并且此方法应始终在循环中使用。

synchronized (obj) {
    while (<condition does not hold>) {
        obj.wait(timeout, nanos);
    }
    ... // Perform action appropriate to condition
}

It does not mention that a InterruptedException needs to be handeled here. 它没有提到需要在此处处理InterruptedException Does that imply that the wait method may spontaniously wakes up without throwing one. 这是否意味着wait方法可以自发地唤醒而不会抛出该方法。

I'd had a look around but didn't find anything specific about how the wakeup is actually processed. 我四处张望,但没有发现有关唤醒实际处理方式的任何具体信息。

As spurious interrupts are not a thing (or so I have read), I believe that is the case. 由于虚假中断不是问题(或者我已经读过),所以我相信情况就是如此。 I am just looking for a confirmation of this. 我只是在寻找确认。

Usually obj.wait(...) should wait until someone calls obj.notify() (or until the timeout is reached), but as the documentation states: 通常, obj.wait(...)应该等待,直到有人调用obj.notify() (或直到达到超时)为止,但是如文档所述:

A thread can wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. 线程可以唤醒,而不会被通知,中断或超时,即所谓的虚假唤醒。 While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied. 尽管在实践中这种情况很少发生,但是应用程序必须通过测试应该导致线程唤醒的条件来防范它,并在条件不满足时继续等待。 See the example below 参见下面的例子

Due to spurious wakeup the thread might wakeup without being notified. 由于虚假唤醒 ,线程可能会在未通知的情况下唤醒。 That is why it is essential to check the guard condition of the monitor in a loop (example taken from the javadoc as well): 这就是为什么必须循环检查监视器的保护条件的原因(示例也取自javadoc):

synchronized (obj) {
  while (<condition does not hold> and <timeout not exceeded>) {
    long timeoutMillis = ... ; // recompute timeout values
    int nanos = ... ;
    obj.wait(timeoutMillis, nanos);
  }
  ... // Perform action appropriate to condition or timeout
}

If you're using a timeout, you should check, if the timeout is exceeded as well. 如果您使用的是超时,则应检查是否也超过了超时时间。

This has nothing to do with handling interrupted exceptions. 这与处理中断的异常无关。 Those won't be thrown spuriously, but only if the current thread is really interrupted. 那些不会被虚假地抛出,只有当当前线程确实被中断时才抛出。 That is in your spurious -loop you don't need to add handling for InterruptedException 那就是在您的虚假循环中,您不需要为InterruptedException添加处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM