1. 饿汉式

线程安全,执行效率高,类加载时就会初始化,浪费内存空间

public class Singleton {

    private Singleton() {}

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }
}

2. 懒汉式

线程不安全,懒加载节省内存空间

public class Singleton {

    private Singleton() {}

    private static Singleton instance;

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

3. 双重检查锁 + 禁止指令重排序

线程安全,不会有指令重排序问题,懒加载节省内存空间

memory = allocate() # 分配对象的内存空间
ctorInstance() # 初始化对象
instance = memory # 设置 instance 指向刚分配的内存

指令重排序后可能 2 和 3 顺序调换

public class Singleton {

    private Singleton() {
    }

    private volatile static Singleton instance;

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

4. 静态内部类

线程安全,调用 getInstance() 才会加载静态内部类

public class Singleton {

    private Singleton() {
    }

    private static class SingletonInstance {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static synchronized Singleton getInstance() {
        return SingletonInstance.INSTANCE;
    }
}

5. 枚举

线程安全,由 JVM 保证单例

public class Singleton {

    private Singleton() {
    }

    public static Singleton getInstance() {
        return Singleton.INSTANCE.getInstance();
    }

    private enum Singleton {
        INSTANCE;

        private final Singleton singleton;

        Singleton() {
            singleton = new Singleton();
        }

        public Singleton getInstance() {
            return singleton;
        }
    }
}

Q.E.D.


盛年不重来,一日难再晨。