• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Rajanand Pandaraparambil Kuttappan
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Rajanand Pandaraparambil Kuttappan
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And also I think wait(), notify(). notifyAll() are not part of OCP-JP syllabus anymore. Please check.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic