The short answer is that is depends on what you are doing.
If the goal of the synchronized block is simply to ensure that access / updates to a data structure are performed safely, then notify()
or notifyAll()
serves no purpose.
On the other hand, if the goal is to implement a "condition variable" then the notify()
or notifyAll()
calls work with a wait
call like this ... for example:
private boolean flag;
private final Object mutex = new Object();
public void awaitFlag(boolean flag) {
synchronized (mutex) {
while (this.flag != flag) {
mutex.wait();
}
}
}
public void setFlag(boolean flag) {
synchronized (mutex) {
this.flag = flag;
mutex.notifyAll();
}
}
The above implements a simple mechanism where threads call awaitFlag()
to wait for the flag
to become true
or false
. When another thread calls setFlag()
to change the flag, all of the threads that are currently waiting for the flag to change will get woken up by the notifyAll()
. This is an example where the notifyAll()
is essential to the working of the code.
So to understand whether the notify
or notifyAll
code is necessary, you need to figure out if some other code might call wait
on the same mutex / lock object.