简体   繁体   English

Java-同步需要挥发性吗?

[英]Java - is volatile required with synchronized?

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? x是否需要挥发? 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"? 我知道同步保证了原子性,但是我不确定可见性...是否执行锁->修改->解锁->锁保证,第二个锁之后x的值将为“新鲜”?

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. 不,不是的, synchronized已经插入了一个内存屏障,因此考虑到其他线程将在同一锁上进行同步,所有线程将看到当前线程执行的更新。

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). 就像同步的一样,易失性具有附加的内存屏障-根据CPU的不同,它是存储/加载/完全屏障,可确保一个线程的更新对其他线程可见。 I assume this is performed with cpu cache invalidation . 我假设这是通过cpu缓存失效执行的

EDIT From what I've just read, the store buffers are flushed to the CPU cache, and this is how the visibility is achieved. 编辑从我刚刚阅读的内容来看,存储缓冲区被刷新到CPU缓存,这就是实现可见性的方式。

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. 简化答案:如果线程A更新了一个字段然后释放了一个锁,那么在线程B获得相同的锁之后,将保证线程B将看到更新。

Note, "release a lock" means exit a synchronized block, and "acquire the same lock" means synchronize on the same object. 注意,“释放锁”表示退出synchronized块,而“获取相同的锁”表示在同一对象上同步。

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

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