why wait() always in a loop

As we know ,jdk API doc suggests to use wait() always in a loop as below:

 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();
         ... // Perform action appropriate to condition
     }

 

But what is a spurious wakeup? two understandings which I think both make sense.

1. Sometimes, one might have several threads waiting on the same object. Those threads may be interested in different aspects of that object.   Say one thread does a notifyAll() on an object, to notify that there have been changes to one particular aspect. All waiting threads will wake up, but only some of  them will be interested in the aspect that has changed; the remainder will have experienced a "spurious wake-up".

2. For inexplicable reasons it is possible for threads to wake up even if notify() and notifyAll() has not been called. This is known as spurious wakeups. Wakeups without any reason.

 

And we can also find some information in Java Language Spec:

 

An internal action by the implementation. Implementations are permitted,
although not encouraged, to perform ``spurious wake-ups'' -- to remove
threads from wait sets and thus enable resumption without explicit instructions
to do so. Notice that this provision necessitates the Java coding practice
of using wait only within loops that terminate only when some logical
condition that the thread is waiting for holds.

你可能感兴趣的:(jdk,thread,UP)