Why can wait and notify only be synchronized?

Foreword

wait and notify must be in the synchronized block, otherwise an IllegalMonitorStateException will be thrown.

the reason

Code example

class BlockingQueue {
    Queue<String> buffer = new LinkedList<String>();

    public void give(String data) {
        buffer.add(data);
        notify();                   
    }

    public String take() throws InterruptedException {
        while (buffer.isEmpty())    
            wait();
        return buffer.remove();
    }
}

The problem with the code example

A consumer calls take and finds buffer.isEmpty.
Before the consumer calls wait, due to cpu scheduling, the consumer thread is suspended, the producer calls give, and then notify.
Then the consumer calls wait (note that due to the wrong conditional judgment, the wait call is after notify, which is the key).
If unfortunately, the producer no longer produces messages after producing a message, then the consumer will hang all the time, unable to consume, causing a deadlock.

The essential

Always make give / notify and take / wait atomic operations. wait / notify is the communication between threads. They have a race condition. We must ensure that we wait only when the conditions are met. In other words, if no lock is added, then the wait condition may not be satisfied when wait is called (as above). Due to the wait under the wrong conditions, then it may never be notified, so we need to force wait / notify in synchronized.

Guess you like

Origin www.cnblogs.com/jichi/p/12694173.html