简体   繁体   English

同步不同的对象可见性

[英]synchronize on different object visibility

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? 我知道在方法1和方法2中使用不同的锁定来编辑a,b,c和d会出现问题,但是问题是方法1刷新的更改对方法1可见吗? because they don't use the same lock. 因为它们不使用相同的锁。

If you only read a , on x64 this will happen to work as memory barriers are not limited to specific memory locations. 如果你只读a ,在x64会出现这种情况的工作内存屏障一样不限于特定内存位置。 However, my understanding is that Java doesn't guarantee this will be thread safe as the locks apply to different objects. 但是,我的理解是,由于锁适用于不同的对象,因此Java无法保证线程安全。 Certainly, if you increment a in the first method, it won't be thread safe. 当然,如果您在第一种方法中增加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 ? 我知道在方法1和方法2中使用不同的锁定来编辑a,b,c和d会出现问题,但是问题是方法1刷新的更改对方法1可见吗? because they don't use the same lock. 因为它们不使用相同的锁。

Without any other synchronization, Java provides no guarantees about whether or when a modification to Aa 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. 如果没有其他任何同步,Java将无法保证一个线程中通过A.method2()Aa进行的修改是否或何时对A.method1()在不同线程中的synchronized块内部或外部可见。 。 A program in which that question arises is not properly synchronized, so its behavior is undefined. 出现该问题的程序未正确同步,因此其行为未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM