Java 1/23种 Singleton(单态) 设计模式 (转)
Double-checked locking and the Singleton pattern
A comprehensive look at this broken programming idiom
Part 1 and Part 2.The Singleton creation pattern is a common programming idiom. When used with multiple threads, you must use some type of synchronization. In an effort to create more efficient code, Java programmers created the double-checked locking idiom to be used with the Singleton creation pattern to limit how much code is synchronized. However, due to some little-known details of the Java memory model, this double-checked locking idiom is not guaranteed to work. Instead of failing consistently, it will fail sporadically. In addition, the reasons for its failure are not obvious and involve intimate details of the Java memory model. These facts make a code failure due to double-checked locking very difficult to track down. In the remainder of this article, we'll examine the double-checked locking idiom in detail to understand just where it breaks down.
Listing 4. Double-checked locking example
instance=new Singleton(); is compiled by the JIT compiler. In addition, I've provided a simple constructor to make it clear when the constructor is run in the assembly code.
String object has the value "hello" at //2. If it doesn't, the StringReader thread prints out a message and stops. If the String class is immutable, you should never see any output from this program. The only way for StringReader to see the str reference to be anything other than a String object with "hello" as its value is if the problem of out-of-order writes occurs.Running this code on old JVMs like Sun JDK 1.2.1 results in the out-of-order write problem, and thus, a non-immutable String.
ThreadLocal and offers tips for exploiting its power.
Am I correct? Please, comment.
// Code.
public class Singleton
{
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance()
{
if (instance == null)
synchronized (Singleton.class)
if (instance == null)
instance = createInstance();
return instance;
}
private static Singleton createInstance()
{
return new Singleton();
}
Posted by Taset on 10 March 2011
Report abuse
Hi MrKK,
Nice article. From your article, I got a question. please clarify.
'Out-of-order writes' can cause issue with any Synchronized blocks (that creates objects). It is not just with the Singletons. Right?
If this is the case, then single Synchronized blocks will never serve the purpose. We always need to go with nested Synchronized blocks. Is this correct statement? Please confirm?
Thanks,
Kalyan K Gondrala
Posted by KalyanKGondrala on 30 December 2010
Report abuse
Hi Mrkk, Can you please let me know the section which says that DCL is fixed. Thanks - Roy
Posted by MDABPM on 13 October 2010
Report abuse
http://jcp.org/en/jsr/detail?id=133
supposedly this is fixed in java 5
Posted by mrkk on 27 August 2010
Report abuse