2

I was reading about wait and notify in Java.

I will explain with a small example:

@Override
    public void run() {
        synchronized (msg) {
            try{
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" processed: "+msg.getMsg());
        }
    }

Here it says that when we do synchronized (msg). The current thread T1 will take a lock on the msg Object.

So the lock can be released via 2 ways :

  1. After the synchronized block is completed
  2. when the wait() is called by T1 ??

And if some another thread calls notify() and woke up the the thread T1, T1 will again gain access to lock on msg object?

Nicky
  • 1,025
  • 3
  • 15
  • 29
  • it is not necessary that T1 starts executing immediately after it has been notified, it competes with other thread waiting to access the lock on object. – nitnamby May 11 '18 at 07:21

2 Answers2

3

Yes, T1 will release the lock when wait, and it has to re-aquire the lock after getting notified. See the details in java language specification.

And, the wait method should be called in a while loop.

 synchronized (obj) {
     while (<condition does not hold>)
         obj.wait();
     ... // Perform action appropriate to condition
 }
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

Lock is released after invoking wait().

And if some another thread calls notify() and woke up the the thread T1, T1 will again gain access to lock on msg object?

It won't gain access to lock automatically. It has to compete with other Threads.

On notify() ( from javadocs) :

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object. The awakened thread will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; for example, the awakened thread enjoys no reliable privilege or disadvantage in being the next thread to lock this object.

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211