Volatile variable explanation in Java docs

坚强是说给别人听的谎言 提交于 2019-11-30 15:44:07

问题


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

This is mentioned at http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html

Can someone please provide an example of this?

This first gave me an impression that the thread that reads a volatile variable will synchronize with the writer thread and wait until the write is done. But that clearly is not the case.

An example would help a lot and be much appreciated.

Thanks, Mustafa


回答1:


Let's say you have the following class:

public class Shared {
    public int a;
    public int b;
    public volatile int c;
}

Now let's say that thread A has a reference to an instance of this class and does

shared.a = 1;
shared.b = 2;
shared.c = 3;

And let's say that thread B has a reference to the same instance and does

display(c);
display(b);
display(a);

Then, if the value displayed for c is 3 (i.e. if the write of thread A has happened before the read of thread B), then it's guaranteed by the Java memory model that 2 and 1 will also be displayed for b and a respectively, because all the actions of thread A that have been made prior to the write to the volatile c are guaranteed to be visible by a thread that has read the new value of c.



来源:https://stackoverflow.com/questions/19738651/volatile-variable-explanation-in-java-docs

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