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?
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.
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.
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.
wait() , this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With