Reading \"Java Concurrency In Practice\", there\'s this part in section 3.5:
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
This example comes under "A reference to the object containing the final field did not escape the constructor"
When you instantiate a new Holder object with the new operator,
please refer for above: http://www.artima.com/designtechniques/initializationP.html
Assume: 1st Thread starts 10:00 am, it calls instatied the Holder object by making the call of new Holer(42), 1) the Java virtual machine first will allocate (at least) enough space on the heap to hold all the instance variables declared in Holder and its superclasses. -- it will 10:01 time 2) Second, the virtual machine will initialize all the instance variables to their default initial values -- it will start 10:02 time 3) Third, the virtual machine will invoke the method in the Holder class.-- it will start 10:04 time
Now Thread2 started at --> 10:02:01 time, and it will make a call assertSanity() 10:03, by that time n was initialized with default of Zero, Second thread reading the stale data.
//unsafe publication public Holder holder;
if you make the public final Holder holder will resolve this issue
or
private int n; if you make the private final int n; will resole this issue.
please refer : http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html under section of How do final fields work under the new JMM?