在 JSR 133 cooking 书 http://g.oswego.edu/dl/jmm/cookbook.html 中
在插入障碍章节中:
-Issue a StoreStore barrier before each volatile store.
-Issue a StoreStore barrier after all stores but before return from any constructor for any class with a final field.
-Issue a StoreLoad barrier after each volatile store.
-Issue LoadLoad and LoadStore barriers after each volatile load.
-Issue an ExitEnter barrier either before each MonitorEnter or after each MonitorExit.
-Issue EnterLoad and EnterStore barriers after each MonitorEnter.
-Issue StoreExit and LoadExit barriers before each MonitorExit.
-If on a processor that does not intrinsically provide ordering on indirect loads, issue a LoadLoad barrier before each load of a final fields.
但是,在 volatile 写入之前没有加载存储屏障?那么在 volatile 写入之后可以重新排序加载吗?
所以下面的方法不起作用?
Init a = 3
V = false
Thread1
x = a
V = true
Thread2
If (V equal true)
a = -1
其中 V 是 volatile 的,a 是普通变量。
线程 1 可能会将 a to x 读为 -1? 这遵循发生在规则之前,因为如果线程 2 将 V 读取为 ture,则 x = a 发生在 a = -1 之前?
最佳答案
我也有同样的问题,但找不到答案,所以我问了作者,这是他的回复,“在你问的情况下省略 LoadStore 的原因是它总是被尾随的 StoreLoad 覆盖。(仅适用于 volatile ,并使用此处考虑的存储后与预加载完整栅栏映射)”
我的理解: “在每个 volatile 存储之后发出 StoreLoad 屏障”,每个架构上的 StoreLoad 都是通过完整内存栅栏实现的(您可以在同一页面的多处理器部分中检查这一点),因此所有先前的加载都不能通过加载/存储重新排序以下 volatile 存储。
关于java - JAVA中 volatile 写入之前是否存在LoadStore内存屏障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31957237/