开发者

Implementation of Atomic wait in Java

The following is a translation of an at开发者_Go百科omic wait in Java. Here what is the need for while? Isn't if sufficient?

///<await (condition) statements; > 

synchronized(obj)
{ 
      while ( !condition) 
      { 
         obj.wait();
      }
      statements;
}


There are actually two reasons why you need it.

Firstly, if a monitor owner calls notifyAll(), all waiting threads are waken up one after another, so if one of the previous threads changed the condition your assumption about it will be not true anymore.

The second reason is Spurious wakeup. As most JVM implementations rely on operating system threading model and some of them allow spurious wakeups (in sake of performance), you need to be ready to such case.


You need the while, because just because someone sent you a notify does not mean that the condition is now true (or is still true).

All notify does (or is supposed to do) is tell the waiting threads (of which there can be many, with different conditions to wait for, even on the same monitor) that now would be a good time to re-evaluate if they still need to wait.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜