• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Wait and Notify

 
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23956
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't count your weasels before they've popped. And now for a mulberry bush related tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic