Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization question.  RSS feed

 
Bala Mohan
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joe Ess
Bartender
Posts: 9406
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bala Mohan
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the answers.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!