Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the notify method be inside a synchronized block?

Consider the following code :-

class CalculateSeries implements Runnable{
    int total;
    public void run(){
        synchronized(this){                          // *LINE 1* 
            for(int i = 1; i <= 10000; i++) {
                total += i;
            }

            notify(); //Notify all the threads waiting on this instance of the class to wake up
        }
    }
} 

Another class is waiting on an instance of this class by getting the lock on it inside a synchronized block. But if I don't keep the code in run method in a synchronized block, then I get IllegalMonitorStateException.

notify() should mean to give signal to all the threads waiting. Then why should it be inside synchronized block?

like image 929
whitehat Avatar asked Jan 11 '12 09:01

whitehat


People also ask

Why wait notify notifyAll must be called inside a synchronized method block?

If no threads are waiting in the waiting queue, then notify() and notifyAll() have no effect. Before calling the notify() or notifyAll() method of an object, a thread must own the lock of the object. Hence it must be in one of the object's synchronizedmethods or synchronized block.

Does notify need to be synchronized?

The wait() and notify() methods must be called within a synchronized context. As soon as the synchronized block that contains the notify() call finishes, the lock is then available and the block containing the wait() call in another thread can then continue.

Why wait and notify are used in synchronized block?

wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to waiting state. notify method wakes up a single thread that is waiting on this object's monitor.

Which method must be used in synchronized block?

wait() , this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown.


1 Answers

notify() should mean to give signal to all the threads waiting.

Actually, no. It signals one arbitrarily chosen waiting thread. notifyAll() signals all of them.

Then why should it be inside synchronized block?

Because waiting doesn't happen for its own sake. You check for a condition and if it's not met, you wait until someone tells you it may now be met (then you check again). Without synchronization, you would have race conditions between checking the condition and actually waiting.

like image 197
Michael Borgwardt Avatar answered Oct 04 '22 03:10

Michael Borgwardt