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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值