"volatile"是否保证任何线程都读取最近写入的值? [英] Does 'volatile' guarantee that any thread reads the most recently written value?

查看:53
本文介绍了"volatile"是否保证任何线程都读取最近写入的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自有效Java一书:

From the book Effective Java:

虽然volatile修饰符不执行互斥,但它保证读取该字段的任何线程都将看到最新写入的值

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 和许多其他来源都声称类似.

SO and many other sources claim similar things.

这是真的吗?

我的意思是真实的,不是一个足够接近的模型,或者仅在x86上,或者仅在Oracle JVM中,或者最近编写的"一些定义.那不是标准的英语解释...

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...

其他消息来源( SO示例)说Java中的volatile就像C ++中的Acquisition/release语义一样.我认为提供报价中的保证.

Other sources (SO example) have said that volatile in Java is like acquire/release semantics in C++. Which I think do not offer the guarantee from the quote.

我发现在 JLS 17.4.4 它表示对易失性变量v的写入(第8.3.1.4节)与任何线程对v的所有后续读取进行同步(其中后续"是根据同步顺序定义的)".但是我不太明白.

I found that in the JLS 17.4.4 it says "A write to a volatile variable v (§8.3.1.4) synchronizes-with all subsequent reads of v by any thread (where "subsequent" is defined according to the synchronization order)." But I don't quite understand.

有很多支持和反对的资料,所以我希望答案能够说服其中的许多(在任何一方)确实是错误的-例如参考或规范,或反例代码./p>

There are quite some sources for and against this, so I'm hoping the answer is able to convince that many of those (on either side) are indeed wrong - for example reference or spec, or counter-example code.

推荐答案

这是真的吗?

我的意思是真实的,不是一个足够接近的模型,或者仅在x86上,或者仅在Oracle JVM中,或者最近编写的"一些定义.那不是标准的英语解释...

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实现为您提供了保证.

Yes, at least in the sense that a correct implementation of Java gives you this guarantee.

除非您使用一些特殊的,实验性的Java编译器/JVM(*),否则您基本上可以将其视为真实.

Unless you are using some exotic, experimental Java compiler/JVM (*), you can essentially take this as true.

来自 JLS 17.4.5 :

在随后每次对该字段进行读取之前,都会对易失字段(第8.3.1.4节)进行写操作.

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


(*)为斯蒂芬C


(*) As Stephen C points out, such an exotic implementation that doesn't implement the memory model semantics described in the language spec can't usefully (or even legally) be described as "Java".

这篇关于"volatile"是否保证任何线程都读取最近写入的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆