Search code examples
javamultithreadingsynchronizedvolatile

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? because they don't use the same lock.


Solution

  • 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.