Java: Are all monitors released when thread waits

2020-02-27 10:42发布

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?

3条回答
何必那么认真
2楼-- · 2020-02-27 11:05

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. [...]
查看更多
▲ chillily
3楼-- · 2020-02-27 11:21

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.

查看更多
可以哭但决不认输i
4楼-- · 2020-02-27 11:27

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

查看更多
登录 后发表回答