论坛首页 Java企业应用论坛

why wait() always in a loop

浏览 2208 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-01-19   最后修改:2010-01-19

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.

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics