Java挥发性和副作用 [英] Java volatile and side-effects

查看:522
本文介绍了Java挥发性和副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Oracle关于原子访问的文档(位于 http://docs.oracle) .com / javase / tutorial / essential / concurrency / atomic.html )说:


happens-before关系...这意味着...当一个线程读取一个volatile变量时,它不仅看到volatile的最新变化,而且还看到导致变化的代码的副作用。


我无法围绕我的头。我理解易失性变量是如何工作的(在= = Java 5),但我想知道如何java决定什么侧面影响导致一个volatile变量的变化。



所以我想我的问题是:给这个保证有什么副作用?



p>

所以我知道,如果线程A修改一个volatile变量,然后线程B读取它,则在写入volatile变量之前发生的所有线程A的写入都是 (即,在线程B中使经过上述写入的变量的高速缓存的值在线程B中无效)。如果我错了,请更正我。

解决方案

大多数多处理器缓存具有一致性机制,因此惩罚不如刷新所有的缓存。



在线程中写入volatile之前写入volatile的任何写操作都会在线程读取volatile之后被读取。


Oracle's documentation on atomic access (at http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html) says this:

"a volatile variable establishes a happens-before relationship... . This means that ... when a thread reads a volatile variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change."

I'm having trouble wrapping my head around that. I understand how volatile variables work (in >= Java 5), but I'm wondering how the java decides what side-affect "led up" to the change of a volatile variable.

So I guess my question is: What side-effects are given this guarantee?

EDIT:

So I've learned that if thread A modifies a volatile variable, and then thread B reads it, all writes from thread A that happened before the write to the volatile variable are "made coherent" with respect to thread B (ie the cached values of variables subject to the afore mentioned writes by thread A are invalidated in thread B). Correct me if I'm wrong.

解决方案

Most multiprocessor caches have coherency mechanisms, so the penalty isn't as bad as flushing all the caches.

Any writes in the thread that wrote to the volatile before doing so will be seen by the thread reading the volatile after having done so.

这篇关于Java挥发性和副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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