是在Java中写入易失性内存屏障 [英] Is a write to a volatile a memory-barrier in Java

查看:127
本文介绍了是在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?

推荐答案

引用易失性变量和其他变量是正确的。我没有意识到,发生之前的传递性是必须由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是写入volatile变量v和a3是从相同的易失性变量读取的。
从happens-before(hb)的定义得出hb(a1,a2)和hb(a3,a4)。
此外,对于挥发物,我们有hb(a2,a3)。现在从hb(a1,a3)的所需的传递性hb开始。因此,易失性变量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.

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

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