Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android / java: synchronized object wait and notify

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

like image 783
Sam Avatar asked May 17 '26 19:05

Sam


2 Answers

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.

like image 180
0xDEADC0DE Avatar answered May 19 '26 08:05

0xDEADC0DE


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.

like image 43
Ravindra babu Avatar answered May 19 '26 08:05

Ravindra babu