We all know that in order to invoke Object.wait(), this call must be placed in synchronized block, otherwise an IllegalMonitorStateException is thrown. But what\'s t
The problem it may cause if you do not synchronize before wait()
is as follows:
makeChangeOnX()
and checks the while condition, and it is true
(x.metCondition()
returns false
, means x.condition
is false
) so it will get inside it. Then just before the wait()
method, another thread goes to setConditionToTrue()
and sets the x.condition
to true
and notifyAll()
.wait()
method (not affected by the notifyAll()
that happened few moments before).
In this case, the 1st thread will stay waiting for another thread to perform setConditionToTrue()
, but that might not happen again.But if you put
synchronized
before the methods that change the object state, this will not happen.
class A {
private Object X;
makeChangeOnX(){
while (! x.getCondition()){
wait();
}
// Do the change
}
setConditionToTrue(){
x.condition = true;
notifyAll();
}
setConditionToFalse(){
x.condition = false;
notifyAll();
}
bool getCondition(){
return x.condition;
}
}