volatile 和 atomic 之间的区别

Differences between volatile and atomic

int value = 0;
volatile boolean done = false;

// Thread A:
value = 1; done = true;

// Thread B:
if (done) System.out.println(value);

这很好,因为 done 被定义为易变的。

除了将 done 定义为 AtomicBoolean 之外,相同的代码怎么样 - 它是否实现了相同的效果?换句话说,原子(RMW)操作除了是原子的和可见的之外,还保证所有先前的写入都刷新到共享内存吗?

int value = 0;
AtomicBoolean done = new AtomicBoolean(false);

// Thread A:
value = 1; done.set(true);

// Thread B:
if (done.get()) System.out.println(value);

From the Javadoc of java.util.concurrent:

The memory effects for accesses and updates of atomics generally follow the rules for volatiles, as stated in The Java Language Specification (17.4 Memory Model):

  • get has the memory effects of reading a volatile variable.
  • set has the memory effects of writing (assigning) a volatile variable.
  • ...

所以在这种情况下,volatileAtomicBoolean没有区别。