Java – why do we need to synchronize on the same object to make notify () work

I got Java lang.IllegalMonitorStateException. I mentioned this problem and it solved my problem The first answer is

To be able to call notify() you need to synchronize on the same object.

synchronized (someObject) {
    someObject.wait();
}

/* different thread / object */
synchronized (someObject) {
    someObject.notify();
}

My question is why do we need to synchronize how it works on the same object advertisement?

As far as I know, as far as I know

synchronized (someObject) {
    someObject.wait();
}

We get the lock of the object someobject, and then we call wait() Now, how can another thread lock the same object to call notify()? What did I miss?

Solution

Why do notifications need locks?

Imagine this:

synchronized(x){
        while(x.count < 4) {
          x.wait();
          //...
        }
}

Imagine being notified elsewhere now without any locks:

//...
println(x.count); // print 3
x.count++;
if(count == 4) 
  x.notify()
//...

At first glance, the whole sound always works as expected But imagine this competitive condition:

//Thread1 enters here
synchronized(x){
     while(x.count < 4) {
         //condition is judged true and thread1 is about to wait 
         //..but..ohh!! Thread2 is prioritized just Now !
         //Thread2,acting on notify block side,notices that with its current count incrementation,//count increases to 4 and therefore a notify is sent.... 
         //but...but x is expected to wait Now !!! for nothing maybe indefinitely !
       x.wait();
       //maybe block here indefinitely waiting for a notify that already occurred!
     }
}

If we have a way to tell the Notifying Party:

Thread 1: "hum... Notification, you are very cute, but I just started to evaluate my situation (x.count < 4) as true, so please... Don't be too stupid to send your expected notification just now (before I wait for my status), otherwise, I would be absurd to wait for things that have passed" thread 2: "OK, ok... In order to maintain consistency, I will lock my logic so that I will send a notification after your waiting call sends our shared lock, so you will receive this notification and allow you to exit the waiting state;)" therefore, always lock the same object waiting to be maintained at the notification end to avoid this situation and keep the relationship consistent. = > The logic that causes notification and the logic that causes waiting should never overlap

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>