3

I get confused on the synchronized method. Look at this code below:

public void waitOne() throws InterruptedException
{
    synchronized (monitor)
    {
        while (!signaled)
        {
           monitor.wait();
        }
    }
}

public void set()
{
    synchronized (monitor)
    {
        signaled = true;
        monitor.notifyAll();
    }
}

Now, from what I understand, synchronized means only 1 thread can access the code inside. If waitOne() is called by main thread and set() is called by child thread, then (from what I understand) it will create deadlock.

This is because main thread never exit synchronized (monitor) because of while (!signaled) { monitor.wait(); } and therefore calling set() from child thread will never able to get into synchronized (monitor)?

Am I right? Or did I miss something? The full code is in here: What is java's equivalent of ManualResetEvent?

Thanks

Community
  • 1
  • 1
Sam
  • 1,826
  • 26
  • 58
  • If you call `wait` on an object that you use to synchronize on, it will allow another thread to access that object. This code will not deadlock – 0xDEADC0DE Apr 20 '17 at 10:06
  • Ahhh... i see... thanks 0xDEADC0DE. Please put a post on it and I'll accept your answer :) – Sam Apr 20 '17 at 10:15

2 Answers2

3

When you call wait on an object that you use to synchronize on, it will release the monitor, allowing​ another thread to obtain it. This code will not deadlock.

shmosel
  • 49,289
  • 6
  • 73
  • 138
0xDEADC0DE
  • 2,453
  • 1
  • 17
  • 22
3

Have a look at documentation of wait() method.

Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

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.

The key point is the thread releases ownership of monitor and hence you won't get deadlock. Child thread can set the value of signaled and can notify main thread.

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