Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full volatile Visibility Guarantee

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?

like image 396
Li Yunlei Avatar asked Aug 20 '19 08:08

Li Yunlei


2 Answers

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.

like image 155
xingbin Avatar answered Sep 29 '22 17:09

xingbin


The only guarantee that this code can give you, is that if a certain thread observes the value written to days, it will also observe the values written to years and months - if there were no update calls again; these are not atomic.

like image 42
Eugene Avatar answered Sep 29 '22 17:09

Eugene