In the exact situation that you described, yes, reading obj inside the foo synchronized block will see the new value set by the previous synchronized block.
The most interesting thing is that this does not always happen in this exact situation. The program is not thread safe, for example, if immediately after bar() exits, the same threads start another bar() , while foo blocks the old object. The bar thread blocks a new object, so two threads are executed simultaneously, both are executed by obj.doWork() on the same new object.
Perhaps we will partially fix it
// suppose this line happens-before foo()/bar() calls MyObject obj = new MyObject(); void foo() while(true) MyObject tmp1 = obj; synchronized(tmp1) MyObject tmp2 = obj; if(tmp2==tmp1) tmp2.doWork(); return; // else retry
this at least ensures that there are no current calls to obj.doWork() on the same object, since obj.doWork() can only be executed in a synchronized block that blocks the same obj
ZhongYu
source share