Java: Are all monitors released when thread waits on an object?

三世轮回 提交于 2019-12-18 14:11:55

问题


Before a thread can wait on an object, it has to acquire a monitor on that object. The monitor is then released, and the thread attempts to re-acquired it once it awakes.

But what happens to other monitors the thread holds when it calls wait?

Consider this example:

   Object a = // ...
   Object b = // ...

   synchronized(a)
   {
       synchronized(b)
       {
           b.wait();
           // continue
       }
   }

When the thread calls b.wait(), will it release the locks on both a and b, or only b?


回答1:


Only b.

The authoritarian source for these type of questions is the Java Language Specification. The relevant section in this case is 17.8 Wait Sets and Notification:

Let thread t be the thread executing the wait method on object m, and let n be the number of lock actions by t on m that have not been matched by unlock actions. One of the following actions occurs.

  • [...]
  • Otherwise, the following sequence occurs:

    1. Thread t is added to the wait set of object m, and performs n unlock actions on m.
    2. [...]



回答2:


From the Java API documentation of the Object class:

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

So, calling b.wait() releases the lock on b only.




回答3:


AFAIK only b. It's a classic source of deadlocks.



来源:https://stackoverflow.com/questions/6265330/java-are-all-monitors-released-when-thread-waits-on-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!