单例模式 为啥越写越复杂

单例模式

  • 饿汉模式
public class Hungry {
    private Hungry() {}
    public static Hungry instance = new Hungry();
    public static Hungry getInstance() {
        return instance;
    }
}

之所以叫做饿汉模式,是因为比较饿,上来就new 一个对象,不管用没用到,也就没有了延迟加载的优点 线程安全,调用效率比较高

  • 优化下饿汉模式,不一开始就new对象了,需要的时候再new
public class Lazy {
    private Lazy(){ }
    public static Lazy instance;
    public static Lazy getInstance(){
        if (instance == null) {
            instance =  new Lazy();
        }
        return instance;
    }
}

这样写,在单线程的情况下没有问题,但是多线程的情况下,有可能返回的不是同一个对象.

  • 优化下,可以支持多线程,给getInstance方法加个sychornized关键字吧
public class Lazy {
    private Lazy(){ }
    public static Lazy instance;
    public static synchronized Lazy getInstance(){
        if (instance == null) {
            instance =  new Lazy();
        }
        return instance;
    }
}
  • 支持多线程了,可是效率不高,每次只能一个线程获取,其他线程等待,再优化下,instance == null时再加锁
public class Lazy {
    private Lazy(){ }
    public static Lazy instance;
    public static Lazy getInstance(){
        if (instance == null) {
            //如果A,B同时到达这个地方,A执行完,instance != null 
            //该B执行了,B又重新new了一次对象
            synchronized (Lazy.class){
                instance = new Lazy();
            }
        }
        return instance;
    }
}
  • 如果A,B同时到达这个地方,A执行完,instance != null 该B执行了,B又重新new了一次对象. 还得继续优化,那么用双层检测吧,所谓双层检测就是判断两次instance == null
public class Lazy {
    private Lazy(){ }
    public static Lazy instance;
    public static Lazy getInstance(){
        if (instance == null) {
            synchronized (Lazy.class){
                if (instance == null) {
                    instance = new Lazy();
                }
            }
        }
        return instance;
    }
}
  • 现在这样可以了? 还是不可以,主要在于instance = new Singleton()这句,这并非是一个原子操作,事实上在 JVM 中这句话大概做了下面 3 件事情。
   1. 给 instance 分配内存 
   2. 调用 Singleton 的构造函数来初始化成员变量
   3. 将instance对象指向分配的内存空间(执行完这步 instance 就为非 null 了)

但是在 JVM 的即时编译器中存在指令重排序的优化。也就是说上面的第二步和第三步的顺序是不能保证的,最终的执行顺序可能是 1-2-3 也可能是 1-3-2。如果是后者,则在 3 执行完毕、2 未执行之前,被线程二抢占了,这时 instance 已经是非 null 了(但却没有初始化),所以线程二会直接返回 instance,然后使用,然后顺理成章地报错

解决方式 只需要将 instance 变量声明成 volatile 就可以了

  • 看下懒汉模式的最终版本
public class Lazy {
    private Lazy(){ }
    public static volatile Lazy instance;
    public static Lazy getInstance(){
        if (instance == null) {
            synchronized (Lazy.class){
                if (instance == null) {
                    instance = new Lazy();
                }
            }
        }
        return instance;
    }
}
  • 静态内部类
public class StaticInnerClass {

    private StaticInnerClass() { }

    private static class InnerHolder {
        private static final StaticInnerClass instance = new StaticInnerClass();
    }

    public static StaticInnerClass getInstance() {
        return InnerHolder.instance;
    }
}

线程安全,延迟加载,推荐使用

  • 枚举单例,推荐写法
public class SingletonExample7 {
    // 私有构造函数
    private SingletonExample7() {}

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

    private enum Singleton {
        INSTANCE;

        private SingletonExample7 singleton;

        // JVM保证这个方法绝对只调用一次
        Singleton() {
            singleton = new SingletonExample7();
        }

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

枚举是最适合实现单例的,线程安全(jvm内部实现,不用我们再加锁),延迟加载,可以防止反射和反序列化破坏单例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值