Java - is volatile required with synchronized?

橙三吉。 提交于 2019-11-26 23:36:58

问题


In the following simple scenario:

class A {
  int x;
  Object lock;

  ...

  public void method(){
    synchronized(lock){
      // modify/read x and act upon its value
    }
  }
}

Does x need to be volatile? I know that synchronized guarantees atomicity, but I am not sure about visibility though... does lock -> modify -> unlock -> lock guarantee, that after the second lock the value of x will be "fresh"?


回答1:


No it does not, synchronised already has a memory barrier inserted after it, so all Threads will see the update that the current thread performs, taking into account that the other threads will synchronise on the same lock.

Volatile, just like synchronised has memory barriers that are attached to it - depending on the cpu it is store/load/full barrier that ensures that an update from one thread is visible to the other(s). I assume this is performed with cpu cache invalidation.

EDIT From what I've just read, the store buffers are flushed to the CPU cache, and this is how the visibility is achieved.




回答2:


Simplified answer: If thread A updates a field and then releases a lock, then thread B will be guaranteed to see the update after thread B has acquired the same lock.

Note, "release a lock" means exit a synchronized block, and "acquire the same lock" means synchronize on the same object.



来源:https://stackoverflow.com/questions/22862226/java-is-volatile-required-with-synchronized

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