aspose file tools*
The moose likes Threads and Synchronization and the fly likes Use of boolean in Wait() and Notify() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Use of boolean in Wait() and Notify()" Watch "Use of boolean in Wait() and Notify()" New topic
Author

Use of boolean in Wait() and Notify()

lavnish lalchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 79
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 ??


lavnish.blogspot.com
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1512
    
    5

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.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
lavnish lalchandani
Ranch Hand

Joined: Feb 28, 2007
Posts: 79
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

Joined: Dec 08, 2010
Posts: 1512
    
    5

You are welcome.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 420
    
    2

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.


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Use of boolean in Wait() and Notify()