据我所知,volatile 背后的底层机制保证不会对操作进行重新排序。但是,我正在努力了解它如何保证可见性。
即线程 A 写入一个值。然后线程 B 从内存中读取它,而不是从缓存中读取它(以保证缓存一致性)。我知道 CAS 正是这样做的,但内存屏障如何实现这一点?
最佳答案
volatile “使用”硬件特定指令来实现它。这是 in-depth article about JSR-133 and Memory Barriers for Compiler Writers
I know CAS does precisely this, but how does a mem barrier achieve this?
因为如果你在 AtomicInteger
中寻找例子,你会看到
private volatile int value;
关于Java - volatile 和可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502540/