简体   繁体   中英

Are spurios wakeups accompanied by an InterruptedException?

The javadoc for Object.wait mentions,

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. Does that imply that the wait method may spontaniously wakes up without throwing one.

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:

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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