单例懒汉实现方式

2020-11-17  本文已影响0人  程序员大亨
package singleton;

/**
 * @program: DesignPatterns
 * @description: 单例设计模式-懒汉实现方式
 * @author: 刘泽
 * @create: 2020-11-17 15:28
 */
public class SingletonLazy {
//    private static SingletonLazy instance;

    /**
     * 私有化构造函数
     */
    private SingletonLazy() {
    }

    /**
     * 第一种多线程下线程不安全
     *
     * @return
     */
///    public static SingletonLzay getInstance() {
///        if (instance == null) {
///            instance = new SingletonLzay();
///        }
///        return instance;
///    }

    /**
     * 第二种
     * 通过加锁保证单例(采用synchronized 加锁对方法加锁有很大的性能开销)
     * 解决办法 :锁粒度放小
     *
     * @return : singleton.SingletonLzay
     * @author: 刘泽
     * @date: 2020/11/17 3:37 下午
     */
//    public static synchronized SingletonLazy getInstance() {
//        if (instance == null) {
//            instance = new SingletonLazy();
//        }
//        return instance;
//    }

    /**
     * 第三种 锁粒度放小
     * DCL 双重检查锁定(保证多线程下保持高性能)
     *
     * @return : singleton.SingletonLazy
     * @author: 刘泽
     * @date: 2020/11/17 3:41 下午
     */
//    public static SingletonLazy getInstance() {
//        if (instance == null) {
//            //A,B
//            synchronized (SingletonLazy.class) {
//                if (instance == null) {
//                    instance = new SingletonLazy();
//                }
//            }
//        }
//        return instance;
//    }
    /**
     * volatile 关键字 禁止指令重排
     */
    private static volatile SingletonLazy instance;
    /**
     * 懒汉
     *
     * @return : singleton.SingletonLazy
     * @author: 刘泽
     * @date: 2020/11/17 4:01 下午
     */
    public static SingletonLazy getSingletonLazy() {
        //第一重校验
        if (instance == null) {
            //加锁
            synchronized (SingletonLazy.class) {
                //第二重校验
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }

    public void property() {
        System.out.println("调用成功");
    }
}

上一篇 下一篇

猜你喜欢

热点阅读