写入 volatile 变量后会发生什么? [英] what happens after writing to a volatile variable?

查看:41
本文介绍了写入 volatile 变量后会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道写入一个易失性变量是否会强制jvm将所有非易失性变量同步到内存中,例如,下面的代码会发生什么:

I wonder if writing to a volatile variable will force jvm to synchronize all non-volatile variables to the memory, so for example, what will happen in the following code:

volatile int x;
int y;

y=5; 
x=10;

x 将被写入内存,但是 y 会发生什么?它也会被写入内存吗?

x will be written to the memory, but what will happen to y ? will it be also written to memory ?

推荐答案

是的,根据 Java 语言规范(第三版)——特别是第 17.4.4 节——看到 x 新值的每个线程如果他们尝试读取它,随后也会看到 y 的新值.不读取 x 的线程不保证会受到影响.

Yes, under the rules of the Java Language Specification (third edition) -- in particular section 17.4.4 -- every thread that sees the new value of x will subsequently also see the new value of y if they try to read it. Threads that don't read x are not guaranteed to be affected.

但是请注意,JLS 第二版 的内存模型中不存在这种保证.在那里,易失性读取和写入对非易失性存储器访问的顺序没有影响.

Beware, however, that this guarantee was not present in the memory model of the second edition of JLS. There, volatile reads and writes had no effect on the ordering of non-volatile memory accesses.

这篇关于写入 volatile 变量后会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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