写入 volatile 是 Java 中的内存屏障吗 [英] Is a write to a volatile a memory-barrier in Java

查看:18
本文介绍了写入 volatile 是 Java 中的内存屏障吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一次演讲中听到,对 volatile 的写入会为线程已写入的每个变量触发内存屏障.那真的正确吗?从 JLS 来看,似乎只有相关的变量被刷新,而不是其他变量.有谁知道什么是真正正确的?可以告诉我 JLS 中的具体位置吗?

I recently heard in a talk that a write to a volatile triggers a memory-barrier for each variable that the thread has written to. Is that really correct? From the JLS, it seems that only the variable concerned gets flushed out, but not others. Does anybody know what is actually correct? Can one point me a concrete location in the JLS?

推荐答案

Volatile 变量的引用和其他变量是正确的.我没有意识到happens-before 的传递性是必须由VM 实现的,而不是遵循定义的.我仍然感到困惑,为什么没有明确说明具有如此深远影响的事物,而实际上是某些定义的必然结果.总结一下:假设您有 4 个这样的操作:

The reference to Volatile variables and other variables was correct. I did not realize that the transitivity of happens-before is something that must be implemented by the VM, not something that follows from the definition. I am still puzzled why something with so far-reaching consequences is not stated clearly but actually a corollary from some definition. To wrap it up: Suppose you have 4 actions like this:

thread1        thread2
a1
a2
                a3
                a4

其中 a2 是对易失性变量 v 的写入,而 a3 是对同一易失性变量 v 的读取.从happens-before (hb) 的定义可以得出hb(a1,a2) 和hb(a3,a4).此外,对于挥发性物质,我们有 hb(a2,a3).现在从 hb 所需的传递性可以得出 hb(a1,a3).因此,对 volatile 变量 v 的写入和后续读取起到了内存屏障的作用.

where a2 is a write to a volatile variable v and a3 is a read from the same volatile variable v. It follows from the definiton of happens-before (hb) that hb(a1,a2) and hb(a3,a4). Also, for volatiles we have hb(a2,a3). It follows now from the required transitivity of hb that hb(a1,a3). So the write and subsequent read of the volatile variable v functions as a memory barrier.

这篇关于写入 volatile 是 Java 中的内存屏障吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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