Forums Register Login

Wait and Notify

+Pie Number of slices to send: Send
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?
+Pie Number of slices to send: Send
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
Never trust an airline that limits their passengers to one carry on iguana. Put this tiny ad in your shoe:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 524 times.
Similar Threads
Sleeping thread takes locks with it?
about monitors
about monitors
notifyAll
Threads interview questions
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:14:50.