I was looking at the following example:
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
// Unsafe publication
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
It is said that because of improper publishing the program will fail in a multi threading environment. What I didn't understand is that lets say Thread 1 calls intitialize() and then calls assertSanity() and Thread 2 calls assertSanity() can they really see different values of n ? or even see holder value as null then a value initialized? It says the problem can be solved by adding final modifier to n. Can someone please help me with an example on how could this go wrong?
My question here seemingly is a duplicate of Improper publication of Java Object Reference but the answer there caters to how volatile modifier of holder can fix the problem. My question is to understand how making n as final fixes the problem.