易失性:为什么要阻止编译器重新排序代码
在java中,据我所知,易失性变量使线程直接读取/写入主CPU(而不是在每个线程的缓存中),因此使其更改对其他线程可见。
我不知道的是:那么,为什么这项工作(易失性)可以阻止编译器/CPU 重新排序代码语句。
谢谢 :)
In java, with my knowledge, volatile variable make a thread reads/writes directly to main CPU (not in cache of each thread), so make its change visibles to other threads.
The thing I don't know is : So, why this work (of volatile) can prevent compiler/CPU reorder statement of code.
thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个很好的例子,说明了禁止重新排序旨在解决的问题(摘自此处):
在此示例中,
v
是易失性的,但x
不是。如果 writer 和 reader 并发执行,并且 reader 看到v
设置为true
,则x
保证为42
。在 Java-5 之前,编译器可以自由地重新排序对x
和v
的写入,因此您可以看到x
为零在您看到v
设置为true
之后。这很令人困惑,并导致了微妙的错误。 Java-5 内存模型通过使易失性写入几乎等同于同步来解决这个问题。Here is a very good example illustrating the issue the prohibition on reordering is aimed to address (taken from here):
In this example,
v
is volatile, butx
is not. If writer and reader are executed concurrently and the reader seesv
set totrue
,x
is guaranteed to be42
. Prior to Java-5, compiler was free to re-order the writes tox
andv
, so you could seex
at zero after you've seenv
set totrue
. This was confusing, and lead to subtle errors. Java-5 memory model addressed this issue by making volatile writes almost equivalent to synchronization.这就是语言的定义方式。通俗地说,在 Java 中标记变量
易失性
专门告诉编译器它不应该重新排序围绕它的语句或优化它的值,因为该值可能会在另一个线程中同时修改。然后,JVM 的特定实现负责遵守此 volatile 修饰符并采取适当的预防措施,以免错误地优化程序。如果您想了解有关语言级保证的更多具体细节,以确保
volatile
正常工作,您可能需要查看 Java 语言规范对 Java 内存模型的描述,它定义了管理线程行为的抽象规则。它还描述了易失性
如何与这些规则交互。希望这有帮助!
That's just how the language is defined. Informally, marking a variable
volatile
in Java specifically tells the compiler that it should not reorder statements around it or optimize on its value, since that value might be modified concurrently in another thread. The particular implementation of the JVM is then responsible for respecting thisvolatile
modifier and taking appropriate precautions not to incorrectly optimize the program.If you'd like more specific details about what language-level guarantees there are to ensure that
volatile
works correctly, you may want to look at the Java Language Specification's description of the Java memory model, which defines the abstract rules governing thread behavior. It also describes howvolatile
interacts with these rules.Hope this helps!