Do you know if there is guaranteed that synchronized block in java is atomic?
Imagine following case
Thread_1,2:
synchronized(object){object.modify();}
(object is shared variable.)
imagine thread_M will change reference to object like
synchronized(object){object = new Object()}
now imagine threads 1 and 2 are competing over getting the lock on object
Is it possible that following would happened:
1. Thread1: read old object
2. ThreadM: modify object reference & release old object lock
3. Thread2: read new object; check lock; lock on it
4. Thread1: check lock (ok cos old object was read); lock on it
now both threads have a lock and modify same (new) object
So to specify my question - is somewhere guaranteed that in synchronized(object) steps (1 and 4) are atomic (like depicted in step 3)?
synchronized(object) { ... }
operates on the variable, when really it is operating on the object to which the variable happens to refer at the instant when the block is entered. – Solomon Slow