gpt4 book ai didi

java - 对 volatile 的写入是 Java 中的内存屏障吗

转载 作者:IT老高 更新时间:2023-10-28 20:41:17 24 4
gpt4 key购买 nike

我最近在一次演讲中听说,对 volatile 的写入会触发线程写入的每个变量的内存屏障。这真的正确吗?从 JLS 来看,似乎只有相关变量被清除,而其他变量则没有。有人知道什么是正确的吗?能否指出 JLS 中的具体位置?

最佳答案

是的,它会启动一个屏障。您可以阅读更多 here .有4种类型,LoadLoad LoadStore StoreStore StoreLoad。

至于你的问题

From the JLS, it seems that only the variable concerned gets flushed out, but not others. Does anybody know what is actually correct?

在 volatile 存储之前发生的所有写入都对任何其他线程可见,前提是其他线程加载此新存储。但是,如果其他线程不加载新值,那么在 volatile 加载之前发生的写入可能会或可能不会被其他线程看到。

举个实际例子

volatile int a =0;
int b = 0;

Thread-1
b = 10;
a = 3;

Thread-2
if(a == 0){
// b can b 10 or 0
}
if(a == 3){
// b is guaranteed to be 10 (according to the JMM)
}

关于java - 对 volatile 的写入是 Java 中的内存屏障吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13688697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com