设计模式 五种不同的单例模式 懒汉式 饿汉式 枚举单例 容器化单例(Spring单例源码分析) 线程单例

原创 疯狂的狮子Li 狮子领域 程序圈 2023-12-18 10:00 发表于辽宁

单例模式

第一种 饿汉式

优点:执行效率高,性能高,没有任何的锁
缺点:某些情况下,可能会造成内存浪费

/**
 * @author LionLi
 */
public class HungrySingleton {

    private static final HungrySingleton hungrySingleton = new HungrySingleton();

    private HungrySingleton(){}

    public static HungrySingleton getInstance(){
        return  hungrySingleton;
    }
}

测试用例与结果

/**
 * @author LionLi
 */
public class Test {
    public static void main(String[] args){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        PrintStream out = System.out;
        executor.execute(() -> out.println(HungrySingleton.getInstance()));
        executor.execute(() -> out.println(HungrySingleton.getInstance()));
        executor.execute(() -> out.println(HungrySingleton.getInstance()));
        executor.execute(() -> out.println(HungrySingleton.getInstance()));
        executor.execute(() -> out.println(HungrySingleton.getInstance()));
        executor.shutdown();
    }
}

图片

图片

多次运行符合要求不会出现问题

第二种 懒汉式

优点:节省了内存,线程安全
缺点:性能低

测试用例以下通用

/**
 * @author LionLi
 */
public class Test {
    public static void main(String[] args){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        PrintStream out = System.out;
        executor.execute(() -> out.println(LazySingletion.getInstance()));
        executor.execute(() -> out.println(LazySingletion.getInstance()));
        executor.execute(() -> out.println(LazySingletion.getInstance()));
        executor.execute(() -> out.println(LazySingletion.getInstance()));
        executor.execute(() -> out.println(LazySingletion.getInstance()));
        executor.shutdown();
    }
}

第一版本

/**
 * @author LionLi
 */
public class LazySingletion {
    private static LazySingletion instance;
    private LazySingletion(){}

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

图片

测试失败无法保证单例

第二版本 增加 synchronized 锁

/**
 * @author LionLi
 */
public class LazySingletion {
    private static LazySingletion instance;
    private LazySingletion(){}

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

图片

图片

测试成功 可以保证单例 但性能较低 所有的线程全都被阻塞到方法外部排队处理

第三版本 细化锁 只锁创建方法提高性能

优点: 性能高了,线程安全了
缺点:可读性难度加大,不够优雅

此方法在各大开源框架源码内最为常见 又名双重校验单例

/**
 * @author LionLi
 */
public class LazySingleton {
    /**
     * volatile 保证原子性具体用法百度
     */
    private volatile static LazySingleton instance;
    private LazySingleton(){}

    public static LazySingleton getInstance(){
        // 检查实例是否已经初始化 如果已经初始化直接返回 避免进入锁提高性能
        if (instance == null) {
            synchronized (LazySingleton.class) {
                // 重新检查是否已经被其他线程初始化
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}

图片

图片

测试成功 可以保证单例 性能还高 可以避免不必要的加锁

第三种 枚举单例

在这种实现方式中,既可以避免多线程同步问题,还可以防止通过反射和反序列化来重新创建新的对象。

Java虚拟机会保证枚举对象的唯一性,因此每一个枚举类型和定义的枚举变量在JVM中都是唯一的。

/**
 * @author LionLi
 */
public enum EnumSingleton {
    INSTANCE;
    private Object data;
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
}

测试代码与结果

/**
 * @author LionLi
 */
public class Test {
    public static void main(String[] args){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        PrintStream out = System.out;
        // 设置一个对象便于查看内存地址
        EnumSingleton.INSTANCE.setData(new Object());
        executor.execute(() -> out.println(EnumSingleton.INSTANCE.getData()));
        executor.execute(() -> out.println(EnumSingleton.INSTANCE.getData()));
        executor.execute(() -> out.println(EnumSingleton.INSTANCE.getData()));
        executor.execute(() -> out.println(EnumSingleton.INSTANCE.getData()));
        executor.execute(() -> out.println(EnumSingleton.INSTANCE.getData()));
        executor.shutdown();
    }
}

图片

图片

测试成功 可以保证单例 代码简单非常优雅

第四种 Spring中的单例模式实现 也可以称为 容器化单例

大家可以通过idea搜索找到 Spring 源码中的 DefaultSingletonBeanRegistry 类 getSingleton 方法 查看 Spring 是如何编写的

图片

这里涉及到三个单例容器:

  • singletonObjects

  • earlySingletonObjects

  • singletonFactories

图片

单例的获取顺序是singletonObjects -> earlySingletonObjects -> singletonFactories 这样的三级缓存

我们发现,在 singletonObjects 中获取 bean的时候,没有使用 synchronized 关键字

而在 singletonFactories 和 earlySingletonObjects 中的操作都是在 synchronized 代码块中完成的,正好和他们各自的数据类型对应

singletonObjects 使用的使用 ConcurrentHashMap 线程安全,而 singletonFactories 和 earlySingletonObjects 使用的是 HashMap 线程不安全。

从字面意思来说:singletonObjects 指单例对象的缓存,singletonFactories 指单例对象工厂的缓存,earlySingletonObjects 指提前曝光的单例对象的缓存。

以上三个构成了三级缓存,Spring 就用这三级缓存巧妙的解决了循环依赖问题。

除了这三个缓存之外 最核心的就是上面讲到的 双重校验单例 写法

图片

第五种 特殊单例 线程单例

顾名思义 保证在所有线程内的单例

常见使用场景 日志框架 确保每个线程内都有一个单例日志实例 保证日志记录和输出的唯一性

提到线程 我们肯定会想到 在线程内最常使用的东西 那就是 TheadLocal 他可以保证线程之间的变量隔离 我们就基于他来实现线程单例

public class ThreadLocalSingleton {
    // 通过 ThreadLocal 的初始化方法 withInitial 初始化对象实例 保证线程唯一
    private static final ThreadLocal<ThreadLocalSingleton> threadLocaLInstance =
            ThreadLocal.withInitial(() -> new ThreadLocalSingleton());

    private ThreadLocalSingleton(){}

    public static ThreadLocalSingleton getInstance(){
        return threadLocaLInstance.get();
    }
}

测试用例与运行结果

/**
 * @author LionLi
 */
public class Test {
    public static void main(String[] args){
        ExecutorService executor = Executors.newFixedThreadPool(5);
        PrintStream out = System.out;
        executor.execute(() -> {
            out.println(ThreadLocalSingleton.getInstance());
            out.println(ThreadLocalSingleton.getInstance());
        });
        executor.execute(() -> {
            out.println(ThreadLocalSingleton.getInstance());
            out.println(ThreadLocalSingleton.getInstance());
        });
        executor.shutdown();
    }
}

图片

测试符合预期 不同线程下的实例是单例的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值