首页 / 资讯中心 / 文章详情

Java单例模式: 几种线程安全写法详解

Java单例模式: 几种线程安全写法详解 ★ FEATURED ARTICLE
单例模式是开发中非常高频的设计模式保证一个类在整个程序中只有唯一的一个实例对象。比如数据库连接池、线程池、配置管理对象都适合使用单例。单例分为饿汉、懒汉两大派系懒汉模式会遇到多线程并发问题如果编码不当会创建多个实例破坏单例特性。本文将结合多线程知识梳理几种线程安全的单例写法分析优缺点。核心问题懒汉模式当多个线程同时调用getInstance()同时判断instance null就会多次 new 对象线程不安全。1.饿汉模式我们来看看代码类加载的同时,创建实例public class SingletonHungry { private static SingletonHungry instancenew SingletonHungry(); private SingletonHungry(){} public static SingletonHungry getInstance(){ return instance; } }2.懒汉模式-单线程版类加载的时候不创建实例. 第一次使用的时候才创建实例.public class SingletonLazy { private static SingletonLazy instancenull; private SingletonLazy(){} public static SingletonLazy getInstance(){ if (instancenull){ instancenew SingletonLazy(); } return instance; } }懒汉模式的优点是:类加载不创建对象, 只有代码真正用到实例的时候才去创建, 节省内存资源❌ 致命缺点多线程环境不安全只能单线程使用多线程场景举例 线程 A 和 线程 B 同时执行if(instance null)线程 A 判断 instance 是 null刚判断完还没执行newCPU 切换到线程 B线程 B 也判断 instance 是 null也准备执行new最终两个线程都会创建对象内存里出现两个不同 Singleton 实例单例模式失效3.懒汉模式-多线程版那我们可以加上synchronized 来改善上述的多线程环境不安全的问题public class SingletonLazy { private static SingletonLazy instancenull; private SingletonLazy(){} public synchronized static SingletonLazy getInstance(){ if (instancenull){ instancenew SingletonLazy(); } return instance; } }4.懒汉模式-多线程版(改进)重点!!!以下代码是在加锁的基础上做了进一步改动:使用双重 if 判定, 降低锁竞争的频率给instance 加上了 volatile.public class SingletonLazy { private static volatile SingletonLazy instancenull; private SingletonLazy(){} public static SingletonLazy getInstance(){ if (instancenull){ //第一层检查 synchronized (SingletonLazy.class){ //加类锁 if (instancenull){ //第二层检查 instancenew SingletonLazy(); } } } return instance; } }1.两层 if 判断作用外层if(instance null)实例已经初始化完成直接 return避免每次都进入锁竞争提升并发性能。内层if(instance null)多个线程同时通过外层 if在 synchronized 处排队一个线程创建完对象释放锁下一个拿到锁的线程进来再次判断防止重复创建对象。2.为什么必须加volatile?instance new SingletonDCL()这行代码不是一条原子指令底层分为三步分配对象内存空间初始化对象执行构造方法将 instance 引用指向分配好的内存JVM 会发生指令重排序。如果发生重排序执行顺序变成1→3→2。 线程 A 执行到new先分配内存引用赋值给 instance对象还没初始化完成。 此时线程 B 走到外层 if发现instance ! null直接返回这个半初始化的对象拿到一个损坏的实例出现 bug。volatile关键字两件事禁止指令重排序保证 new 对象三步不会乱序保证内存可见性一个线程修改 instance其他线程立刻感知最新值。⚠️没有 volatile双重检查锁依然线程不安全✅优点懒加载只有第一次才会竞争锁, 后续调用无锁并发性能高。
阅读完成 · 觉得有帮助?
咨询建站