gpt4 book ai didi

java - 'volatile'是否保证任何线程都读取最近写入的值?

转载 作者:行者123 更新时间:2023-12-03 12:44:03 25 4
gpt4 key购买 nike

从有效的Java书中:

While the volatile modifier performs no mutual exclusion, it guarantees that any thread that reads the field will see the most recently written value


SO和许多其他来源都声称类似。
这是真的吗?
我的意思是说真的,不是一个足够接近的模型,或者仅在x86上,或者仅在Oracle JVM中,或者不是“标准英语”解释的“最近编写的”某些定义,都适用。
其他来源( SO example)表示Java中的volatile类似于C++中的获得/释放语义。我认为 do not从报价中提供了保证。
我发现在 JLS 17.4.4中它说:“对 volatile 变量v(第8.3.1.4节)的写入将与任何线程对v的所有后续读取进行同步(其中,“后续”是根据同步顺序定义的。)但是我不太明白。
有很多支持和反对的来源,所以我希望答案能够说服其中的许多(在任一侧)确实是错误的-例如引用或规范,或反示例代码。

最佳答案

Is this true?

I mean really true, not a close-enough model, or true only on x86, or only in Oracle JVMs, or some definition of "most recently written" that's not the standard English interpretation...


是的,至少在某种意义上,正确的Java实现可为您提供这种保证。
除非您使用一些特殊的,实验性的Java编译器/JVM(*),否则您基本上可以将其视为真实。
JLS 17.4.5:

A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.



(*)与 Stephen C points out一样,这种未实现语言规范中描述的内存模型语义的奇异实现无法有效地(甚至合法地)描述为“Java”。

关于java - 'volatile'是否保证任何线程都读取最近写入的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66653558/

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