Java volatile and side-effects

烂漫一生 提交于 2019-12-20 09:46:09

问题


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.


回答1:


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.




回答2:


Take Double Checked Locking as an example. When you create an object, many things happen under the covers:

MyClass c=new MyClass();

Memory is allocated, the constructor is called, and the memory location is assigned to the variable c. The JVM is allowed to reorder those actions. This causes problems if memory is allocated, the value is assigned, and a thread interrupts and uses the value before the constructor is called.

volatile MyClass c=new MyClass();

Under the 1.5 rules, the assignment is guaranteed to be the last one of those events. The "side effects" are the allocation and the constructor call.



来源:https://stackoverflow.com/questions/9169232/java-volatile-and-side-effects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!