Java单例的几种写法

版权声明:转载请注明来源 https://blog.csdn.net/EllieYaYa/article/details/80193131

单线程写法

public class Singleton {
    private static Singleton uniqueInstance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (null == uniqueInstance) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}

线程安全普通写法

public class Singleton {
    private static Singleton uniqueInstance = new Singleton();
    private Singleton() {}
    public static Singleton getInstance() {
        return uniqueInstance;
    }
}

线程安全装逼写法(关键在volatile)

public class Singleton {
    private volatile static Singleton uniqueInstance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (null == uniqueInstance) {
            synchronized(Singleton.class) {
                if (null == uniqueInstance) {  
                    uniqueInstance = new Singleton();  // volatile禁止了此处的内存分配和复制的重排序指令
                }
            }
        }
        return uniqueInstance;
    }
}

装逼失败的写法 (static等效于线程安全的普通写法)

public class Singleton {
    private static Singleton uniqueInstance;

    static {
        if (null == uniqueInstance) {
            synchronized(Singleton.class) {
                if (null == uniqueInstance) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

猜你喜欢

转载自blog.csdn.net/EllieYaYa/article/details/80193131