synchronize on different object visibility

主宰稳场 提交于 2019-12-24 09:24:45

问题


the following code shows synchronization on different object than this:

public class A {

int a,b,c,d;

public void method1(Object x){
   synchronized(x){
     // is a ,b ,c ,d guarantee visibility ? 
   }
}

   public synchronized void method2() {
        a++;
    }
}

I know there will be a problem to edit a , b ,c ,d with having different lock in method1 and method2 , but the question is the changes flushed by method2 be visible to method1? because they don't use the same lock.


回答1:


If you only read a, on x64 this will happen to work as memory barriers are not limited to specific memory locations. However, my understanding is that Java doesn't guarantee this will be thread safe as the locks apply to different objects. Certainly, if you increment a in the first method, it won't be thread safe.




回答2:


I know there will be a problem to edit a , b ,c ,d with having different lock in method1 and method2 , but the question is the changes flushed by method2 be visible to method1 ? because they don't use the same lock.

Without any other synchronization, Java provides no guarantees about whether or when a modification to A.a performed via A.method2() in one thread would be visible to A.method1(), either inside or outside the synchronized block within, in a different thread. A program in which that question arises is not properly synchronized, so its behavior is undefined.



来源:https://stackoverflow.com/questions/52794312/synchronize-on-different-object-visibility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!