Java: If notify () is always called before a lock is released, how can pending threads get the same lock?

I think I already know the answer to this question, however, I would like to read your opinions to make sure that I really understand how the Java thread machine (or diagram) works.

Imagine that Thread A starts notify () before returning the given value:

public class baz{ // Thread B runs this: public synchronized void bar(){ wait(); } // Thread A runs this: public synchronized int foo(){ notify(); return 11; } } 

notify () is called before Thread A releases the lock (what happens “after” the return 11 ; statement ). So, how can there be a thread B waiting for this lock (using the wait () method) to get a lock that is still held by Thread A? Note that when thread B is notified, the lock has not yet been released by thread A.

So, I think of this situation as follows:

After calling wait (), Thread B will change its state from Run to Wait . After receiving the notification (from the Thread A notify () method), Thread B will return with wait () , change its state to Runnable and try to acquire a lock. Since the lock has not yet been released by thread A, thread B will be locked on the object’s monitor and will transfer its status from Runnable to Blocked . In the end, after Thread A releases the lock, Thread B will receive the lock and pass its state from Locked to Start .

Is it correct? What I want to understand with this question is what happens to the thread that returns from wait () , which is synchronized by the lock already received.

+7
java multithreading
source share
1 answer

Yes, your explanations are correct.

When you call wait() on an object, the calling thread will be added to the wait set object. When it is notify() , it will be removed from this waiting set and perform the lock action on the object (it is within the synchronized block on this object). This blocking action blocks the current thread until it is completed, i.e. blocked the object monitor.

This is the same behavior as two threads when trying to enter a synchronized block on the same object. The first access thread would lock the object monitor, terminating the lock object immediately. The other thread blocks until the blocking action is complete, i.e. after the first thread unlocks the monitor.

+1
source share

All Articles