aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Can a waiting thread be notified without an explicit notify invocation on the synchronized object ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Can a waiting thread be notified without an explicit notify invocation on the synchronized object ?" Watch "Can a waiting thread be notified without an explicit notify invocation on the synchronized object ?" New topic
Author

Can a waiting thread be notified without an explicit notify invocation on the synchronized object ?

Rajanand Pandaraparambil Kuttappan
Greenhorn

Joined: Oct 26, 2011
Posts: 15


The output is :-


laurel: starts running
laurel: going to sleep
hardy: starts running
hardy: going to wait for laurel
laurel: out from sleep
laurel: is exiting run
hardy: IS OUT FROM WAIT ON LAUREL.
hardy: is exiting run


Can any one please explain how the thread 'hardy' came-out from the waiting and who notified on the synchronized object 'laurel'? Please note that there is no laurel.notify() statement anywhere in the code-snippet.

Also if I comment-out the try-catch including the Thread.sleep, hardy waits forever, though laurel completes its execution.

Thanks
Raj


Rajanand P K, Oracle Certified Professional, Java SE 6 Programmer.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

When you wait on a Thread object then you get a notification when the target thread completes. So if Thread A is waiting on Thread B object, then Thread A will be notified when Thread B completes...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rajanand Pandaraparambil Kuttappan
Greenhorn

Joined: Oct 26, 2011
Posts: 15
if Thread A is waiting on Thread B object, then Thread A will be notified when Thread B completes...


So, JLS treats this an exceptional case for the thread being used as a monitor, right? Because, theoretically speaking, if there is an object1.wait() from ThreadA, ThreadA would wait until there comes a object1.notify() from another thread which again synchronized on object1. And, in our case, we do not have an explicit notify call at all.

-Raj
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

You cannot rely on this behavior. This happens because Thread.join has been implemented this way but JLS doesn't specify this behavior. So this behavior might change in the future thus it will not be asked in SCJP exam ...
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
And also I think wait(), notify(). notifyAll() are not part of OCP-JP syllabus anymore. Please check.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can a waiting thread be notified without an explicit notify invocation on the synchronized object ?