Full volatile Visibility Guarantee

Li Yunlei :

I am reading an article about the Java Volatile keyword, got some questions. click here

public class MyClass {
    private int years;
    private int months
    private volatile int days;


    public void update(int years, int months, int days){
        this.years  = years;
        this.months = months;
        this.days   = days;
    }
}

The udpate() method writes three variables, of which only days is volatile.

The full volatile visibility guarantee means, that when a value is written to days, then all variables visible to the thread are also written to main memory. That means, that when a value is written to days, the values of years and months are also written to main memory.

So, what does "all variables visible to the thread" mean? Does it means all variables in thread's stacks? And what does "visible to the thread" mean? How can I know does months and years visible to the thread?

xingbin :

It's all about happens-before relationship.

This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement.

  1. In the same thread,

        this.years  = years;
        this.months = months;
    

    happens-before:

        this.days   = days;
    
  2. In different thread, the write of volatile variable happens-before the reader thread which read the volatile variable.

And, happens-before relationship has transitivity. When the reader thread see the fresh value of volatile variable days, it can also read the fresh value of years and months.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138700&siteId=1
Recommended