• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use of boolean in Wait() and Notify()

 
lavnish lalchandani
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Going through a book on Thread programming saw two different snippets of code ... didn't understand why the second one is better than the first one
FIRST ONE
A member object is used

The first thread comes along and executes this code fragment:

The thread doing the notification comes along and executes this code fragment:


SECOND ONE
In MOST cases, a member variable is checked by the thread doing the waiting and modified by the thread doing the notification. The checking and modification occur inside the synchronized blocks to be sure that no race conditions develop.

This time, two member variables are used:

The first thread comes along and executes this code fragment:

While the first thread is waiting, a second thread comes along and executes this code fragment:


I didnt understand whats the advantage of using a boolean ??
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello lavnish lalchandani,

Please QuoteYourSources.

And yes, second code is better than first one.

Hint : what will happen if one thread invokes notify method, and then another thread enters in waiting state?

I hope this helps.
 
lavnish lalchandani
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got this example from Sams Thread Programming , chap 8 inter thread communication

ok got your point you mean avoid "missed notification" and "early notification" possibility
Thanks
 
Anayonkar Shivalkar
Bartender
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This example is about spurious thread wake up ... which is why some tools will warn you about waits not in loops.

Basically what if your wait just returns without a notify (this is the very rare spurious wake up .. various reasons all edge cases) , in this case you use your boolean to confirm you effectively really were given a wakeup.

If you look at the standard java docs for Object.wait () you'll see this scenario well documented.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic