File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Synchronization question. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Synchronization question." Watch "Synchronization question." New topic
Author

Synchronization question.

Bala Mohan
Greenhorn

Joined: Jul 05, 2002
Posts: 27
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

Joined: Jul 08, 2003
Posts: 24054
    
  13

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.


[Jess in Action][AskingGoodQuestions]
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8262

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.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
Bala Mohan
Greenhorn

Joined: Jul 05, 2002
Posts: 27
Thank you for the answers.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Synchronization question.
 
Similar Threads
Thread - Wait() and Notify();
notify() and notifyAll()
Why call await() inside a while loop instead of inside an if
wait and notify code
No notify for a waiting thread