Full volatile Visibility Guarantee
Asked Answered
J

2

13

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?

Japanese answered 20/8, 2019 at 8:1 Comment(0)
E
6

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.

Extravagancy answered 20/8, 2019 at 8:14 Comment(1)
Note that this (if it is correct) is still a very weak guarantee. It says that you will see some updates, but it does absolutely not say you will always see a consistent year/month/day triplet when reading/using the data. Most prominently, when reading days, months, years (to have the volatile read as the first statement?), someone might have called update() in the meantime you and you might see the result of that call in one or more of your fields. For complete consistency you need to use proper synchronization/locking.Aires
D
1

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.

Desma answered 21/8, 2019 at 19:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.