This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wait and Notify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wait and Notify" Watch "Wait and Notify" New topic

Wait and Notify

Liang Anmian
Ranch Hand

Joined: Jun 25, 2004
Posts: 119
Hi guys,

I have a little problem here. Supposed there are 2 threads. The first thread has a call to wait(), and the second thread has a call to notify(). Now, assume that both calls are synchronized on the same object. If the first thread calls wait(), the second thread will "wake up" the thread with the notify() method. However, since we can't know for sure which thread runs first (it's all up to the thread scheduler), what if the second thread runs first? Doesn't it mean that the notify() method is called before the wait() method? What will happen in this scenario, and any way to prevent this?

Current Status:<br /> <br />SCJP 1.4<br />SCJD (in progress)
Henry Wong

Joined: Sep 28, 2004
Posts: 19926

If a notification is sent and no thread is waiting, then the notification is lost.

This is why you should never use wait/notify without some sort of flag. Basically:

- Never call wait unless you need to. If the notify flag runs first, the notification may be lost, but the first thread won't wait, because the flag should be set.

- Never expect the flag to be set upon return from wait() -- another thread may have done the first point, and not performed a wait.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
subject: Wait and Notify
It's not a secret anymore!