I am trying to make sense of the reason why notify()
method needs to be called for wait()
to resume. Lets take the following pseudo code sample from the producer consumer problem-:
Producer pseudo-code
synchronized(data_structure) {
if(data_structure.isFull()) {
data_structure.wait();
}
produce(data_structure);
notify(); // The consumer thread is only notified, it cannot start execution since it does not have a lock.
}// Only when the producer gives up the lock can the consumer start.
Consumer Pseudo Code
synchronized(data_structure) {
if(data_structure.isEmpty()) {
data_structure.wait();
}
consume(data_structure);
notify(); // The Producer thread does not resume execution from this point, its just notified it can.
}//The producer thread only resumes execution when the consumer thread releases the lock. So what was the point of notify() ?
So my point is that notify()
only notifies the waiting thread, nothing actually happens until the thread calling notify()
releases the lock on that object. So if the waiting thread just keeps waiting and without calling notify()
the lock is released and the waiting thread resumes execution, what would be the harm in that ?
I understand that notify()
needs to be in a synchronized block since to avoid race conditions, but why call in the first place, if nothing happens until the lock is released ?
Its like I have a phone that I am using and another person is waiting for the phone, his only job is waiting for the phone. So when I finish my work and relinquish control of the phone he will obviously know that it is now available, why do I need to tell him its available and then relinquish control ?
By the way, as per my knowledge notifyAll()
gives non-deterministic behavior if there are multiple threads waiting ? Correct me if I am wrong.