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?
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.
In the same thread,
this.years = years;
this.months = months;
happens-before
:
this.days = days;
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With