Java Question :
Coming out of synchronization block automatically does notifyAll(). Is that the expected behavior?
I have tested it and it seems like 1. wh
You shouldn't use a Thread
object as a locking object. See more explanations in question Does java notify waiting threads implicitly?.
Advertisement: Jon Skeet speaks there :) (This is a direct link to the answer in the above linked question.)
There is also another question linked from a comment, now I'll make it more achievable: who and when notify the thread.wait() when thread.join() is called?
What you have discovered is that java.lang.Thread
uses the wait facility internally using itself as a lock. This is documented in the description for the Thread.join() method (not the best place, probably):
This implementation uses a loop of
this.wait
calls conditioned onthis.isAlive
. As a thread terminates thethis.notifyAll
method is invoked. It is recommended that applications not usewait
,notify
, ornotifyAll
on Thread instances.
By the way, if you used a while loop for checking if the condition for waiting has changed as the best practice dictates, that would guard you against such wakeups, though, of course, it is best to just use an Object
as a lock anyway.