Java单例模式写法(懒加载+线程安全)

2020-12-08  本文已影响0人  灰气球

双检锁

public class DoubleCheckLockingSingletonDemo {

    private DoubleCheckLockingSingletonDemo() {
    }

    private static volatile DoubleCheckLockingSingletonDemo instance;

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

}

枚举

public enum EnumSingletonDemo {

    INSTANCE;

    EnumSingletonDemo() {
    }

    public void whateverMethod() {
    }
}

静态内部类

public class InternalStaticClassSingletonDemo {

    private InternalStaticClassSingletonDemo() {
    }

    static class InternalStaticClass {
        public static volatile InternalStaticClassSingletonDemo instance = new InternalStaticClassSingletonDemo();
    }

    public static InternalStaticClassSingletonDemo getInstance() {
        return InternalStaticClass.instance;
    }

}

同步方法

public class SynchronizedFuncSingletonDemo {

    private SynchronizedFuncSingletonDemo() {
    }

    private static SynchronizedFuncSingletonDemo instance;

    public synchronized SynchronizedFuncSingletonDemo getInstance1() {
        if (null == instance) {
            instance = new SynchronizedFuncSingletonDemo();
        }
        return instance;
    }

}

问题

上一篇下一篇

猜你喜欢

热点阅读