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

后端 未结 2 1841
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题