Question

Reading Oracle javadocs for Object.wait() method, I don't quite understand the phrase

place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object.

How many claims can a thread have on a single object? Why do they use "any and all" instead of just "...to relinquish the lock on this object." Further down the javadocs state:

Note that the wait method, as it places the current thread into the wait set for this object, unlocks only this object; any other objects on which the current thread may be synchronized remain locked while the thread waits.

...so just when I thought I could stretch the meaning of "any and all", I realized I could not. Could anyone please help clear this up for me?

Was it helpful?

Solution

You can synchronize on an object multiple times.

synchronized(lock) {
    synchronized(lock) {
        lock.synchronizedMethod();
    }
}

Calling lock.wait() releases all of those.

From the Java Language Specification

A single thread may acquire a lock more than once.

OTHER TIPS

A single thread is allowed to lock the same object multiple times. For each object, the Java virtual machine maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is again incremented to one. Each time the thread acquires a lock on the same object, the count is again incremented. (Only the thread that already owns an object's lock is allowed to lock it again. As mentioned previously, no other thread can lock the object until the owning thread releases the lock.) Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.

synchronized(myLockObjA){
    synchronized(myLockObjB){
        synchronized(myLockObjA){
           //Do something.
           // lock count for myLockObjA = 2 and for myLockObjB = 1
           while(!someCondition)
               myLockObjA.wait(); //lock count for myLockObjA = 0 and for myLockObjB = 1
           //Now the thread will have to acquire lock on myLockObjA again after getting a wake up call by notify/notifyAll method. 
         }
    }
}

More information can be found here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top