Frankly, this is a continue of this my question, inspired by this answer: https://mcmap.net/q/15885/-cdi-postconstruct-and-volatile-fields
Let's suppose we have a class:
public class Foo {
private Integer x;
public void setX(Integer x) {
this.x = x;
}
public Integer getX() {
return this.x;
}
}
And let us consider a very specific scenario, when we have just two threads which interact with the x
variable:
At time 1, a thread T1 is created
At time 2, T1 sets the value: foo.setX(123);
At time 3, a thread T2 is created
At time 4, T2 reads the value: foo.getX();
No other threads interact with this value. Both operations happen only once.
So there is no apparent x
value read operations before the thread T2 does his job.
The question is: does any auto optimisation for L cache exist which can cache null
value of the x
variable, so the thread T2
will read its cached value?
In other words, do we need the volatile
modifier in this particular scenario?