Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wait and Notify

 
Liang Anmian
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Henry Wong
author
Marshal
Pie
Posts: 21197
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic