say we have this
// This is trivially immutable.
public class Foo {
private String bar;
public Foo(String bar) {
this.bar = bar;
}
pu
From the link posted in comments:
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
}
}
}
One thread may call writer()
and and another thread may call reader()
. The if condition in reader() could evaluate to true, but becuase y is not final the object initalizion may not have completely finished (so the object has not been safely published yet), and thus int j = 0
could happen as it has not been initialized.