本文介绍了Java - 同步时是否需要volatile?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下简单场景中:

class A {
  int x;
  Object lock;

  ...

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

x是否需要波动?我知道同步保证原子性,但我不确定可见性虽然...确实锁定 - >修改 - >解锁 - >锁定保证,在第二次锁定后,x的值将是新鲜?

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"?

推荐答案

不,它没有,同步之后已经插入了内存屏障,所以所有线程将看到当前线程执行的更新,考虑到其他线程将在同一个锁上同步。

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有附加的内存屏障一样 - 取决于它是存储/加载/完全屏障的cpu,它确保来自一个线程的更新是对其他人可见。 我认为这是通过cpu cache invalidation 执行的。

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.

编辑
从我刚刚开始读取,存储缓冲区被刷新到CPU缓存,这就是实现可见性的方式。

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

这篇关于Java - 同步时是否需要volatile?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:29