public class Holder {
private int n;
public Holder(int n) {
this.n = n;
}
public void assertSanity() {
if(n != n) {
throw new AssertionError("something is wrong!");
}
}
}
This code snippet is from JCIP Listing 3.15. On the foot note it said:
While it may seem that field values set in a constructor are the first values written to those fields and therefore that there are no "older" values to see as stale values, the Object constructor first writes the default values to all fields before subclass constructors run. It is therefore possible to see the default value for a field as a stale value.
I am confused if the class has only these variable and method, how could it be not thread safe, even with subclass instantiated? Because the method call to assertSanity
will be blocked by the constructor method, so I think it will always be set correctly when you call that method.
It will be great help if you can build a possible sub-class leading to a race condition here.