class FinalFieldExample {
final int x;
int y;
static FinalFieldExample f;
public FinalFieldExample() {
x = 3;
y = 4;
}
static void writer() {
f = new FinalFieldExample();
}
static void reader() {
if (f != null) {
int i = f.x; // guaranteed to see 3
int j = f.y; // could see 0
}
}
}
I share the same confusion as the author of this question while reading the JLS chapter 17 on JMM. I can literally understand in the described situation f.y could be 0. But this is just like reciting a rule without any serious thinking on it.
It would be really hard to remember the rule if I haven't seen a mistake caused by not following the rule.I have searched through the net but cannot find anyone who gave an example for a situation where f.y could be 0, nor can I come up with mine one example.
I think it may only happens in some rare situation but I am just eager to see one.Hope anyone could give a code demo where f.y could be proved to have been at least once the value of 0.