I was reading this article about \"Double-Checked locking\" and out of the main topic of the article I was wondering why at some point of the article the author uses the nex
The article refers to the pre-5.0 Java memory model (JMM). Under that model leaving a synchronised block forced writes out to main memory. So it appears to be an attempt to make sure that the Singleton object is pushed out before the reference to it. However, it doesn't quite work because the write to instance can be moved up into the block - the roach motel.
However, the pre-5.0 model was never correctly implemented. 1.4 should follow the 5.0 model. Classes are initialised lazily, so you might as well just write
public static final Singleton instance = new Singleton();
Or better, don't use singletons for they are evil.
I cover a bunch of this here:
http://tech.puredanger.com/2007/06/15/double-checked-locking/
Following the John Skeet Recommendation:
However, to go deeper into the subject I'd recommend Bill Pugh's article. And then never attempt it :)
And here is the key for the second sync block:
This code puts construction of the Helper object inside an inner synchronized block. The intuitive idea here is that there should be a memory barrier at the point where synchronization is released, and that should prevent the reordering of the initialization of the Helper object and the assignment to the field helper.
So basically, with the Inner sync block, we are trying to "cheat" the JMM creating the Instance inside the sync block, to force the JMM to execute that allocation before the sync block finished. But the problem here is that the JMM is heading us up and is moving the assigment that is before the sync block inside the sync block, moving our problem back to the beginnig.
This is what i understood from those articles, really interesting and once more thanks for the replies.
All right, but the article said that
The code in Listing 7 doesn't work because of the current definition of the memory model. The Java Language Specification (JLS) demands that code within a synchronized block not be moved out of a synchronized block. However, it does not say that code not in a synchronized block cannot be moved into a synchronized block.
And also seems like the JVM makes the next translation to "pseudo-code" in ASM:
public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { //1 Singleton inst = instance; //2 if (inst == null) { synchronized(Singleton.class) { //3 //inst = new Singleton(); //4 instance = new Singleton(); } //instance = inst; //5 } } } return instance; }
So far, the point of no writes after the "instance=inst" is not accomplished?
I will read now the article, thanks for the link.