In my java program, when I code
synchronized(a){
a = 55;
a.wait();
}
It gives run time exception java.lang.IllegalMonitorStateException on a.wait(); statement. However a=55 runs successfully.
But if I code as
synchronized(a){
a.wait();
a = 55;
}
then it runs perfectly without any exception. why so?
Because
ais pointing to a different object after reassignment, and is not being synchronized on.In other words, there are two objects,
val1andval2that are both assigned to the variablea. You synchronize onval1but in the first example call wait onval2. The monitor you use is attached to the object, not its variable.You should thus avoid synchronizing by referencing a non-final variable. This leads to your confusion. If the field is mutable, use another lock, for example:
Ideally your scenario is just for learning though.
wait()andnotify()are primitives and shouldn’t be used unless as an exercise or for building your own concurrency library. If it’s for real code, use a higher level mechanism injava.util.concurrent.