Java synchronization is doing auto notify on exit ? Is this expected?

后端 未结 2 1819
孤独总比滥情好
孤独总比滥情好 2020-12-21 04:34

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

相关标签:
2条回答
  • 2020-12-21 05:01

    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?

    0 讨论(0)
  • 2020-12-21 05:06

    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 on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll 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.

    0 讨论(0)
提交回复
热议问题