Java的singleton模式的double-check问题

以下是double-checked locking的java代码:
public class Singleton {
    private Singleton instance = null;
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(this) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


但double-check在J2SE 1.4或早期版本在多线程或者JVM调优时由于out-of-order writes,是不可用的。

这个问题在J2SE 5.0中已经被修复,可以使用volatile关键字来保证多线程下的单例。
public class Singleton {
    private volatile Singleton instance = null;
    public Singleton getInstance() {
        if (instance == null) {
            synchronized(this) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}


推荐方法是Initialization on Demand Holder(IODH),详见 http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

public class Singleton {
    static class SingletonHolder {
        static Singleton instance = new Singleton();
    }
    
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}

你可能感兴趣的:(java,jvm,多线程,J2SE)