Hi, I came across this in 'The Java Programming Language, 3ed' by Arnold,Gosling,Holmes (Section 10.4, page 244). ================================================ There is a standard pattern that is important to use with wait and notification. The thread waiting for a condition should always do something like this: Synchronized void doWhenCondition () { while (!condition) wait ();
.. Do what must be done when the condition is true .. } .... The condition test should always be in a loop. Never assume that being awakened means that the condition has been satisfied - it may have changed again since being satisfied. In other words, don't change the while to an if. .... ====================================== Can someone explain this reason 'why it should be a 'while' instead of an 'if'. Thanks, Bala.
Ernest Friedman-Hill
author and iconoclast
Marshal
Very briefly: because the "condition" may still be false when "wait()" returns. If you're waiting for something to become true, then wait() returning isn't enough; you have to check the condition again -- and a loop is obviously the simplest way to do this.
A call to wait() can be interrupted by another thread. Should it be interrupted and the condition not be satisfied you want to check that condition again.