[英]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);
This is fine, since done is defined as volatile.这很好,因为 done 被定义为 volatile。
What about the same code, except that done is defined as an AtomicBoolean - does it achieve the same effect?相同的代码呢,除了 done 被定义为 AtomicBoolean 之外 - 它是否达到相同的效果? In other words, do atomic (RMW) operations, apart from being atomic and visible, also guarantee that all previous write are flushed to shared memory?
换句话说,原子(RMW)操作除了原子和可见之外,是否还保证所有先前的写入都刷新到共享的 memory?
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
: 来自
java.util.concurrent
的 Javadoc :
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):
用于访问和更新原子的 memory 效果通常遵循 volatile 的规则,如 Java 语言规范(17.4 Memory 模型)中所述
- get has the memory effects of reading a volatile variable.
get 具有读取 volatile 变量的 memory 效果。
- set has the memory effects of writing (assigning) a volatile variable.
set 具有写入(分配)易失性变量的 memory 效果。
- ...
...
So in this case, there is no difference between volatile
and AtomicBoolean
.所以在这种情况下,
volatile
和AtomicBoolean
之间没有区别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.