Java单例模式的8种写法(推荐)

作者:Zerone Wong 时间:2023-01-06 14:23:27 

单例:Singleton,是指仅仅被实例化一次的类。

饿汉单例设计模式

一、饿汉设计模式


public class SingletonHungry {
private final static SingletonHungry INSTANCE = new SingletonHungry();

private SingletonHungry() {
}

public static SingletonHungry getInstance() {
return INSTANCE;
}
}

因为单例对象一开始就初始化了,不会出现线程安全的问题。

PS:因为我们只需要初始化1次,所以给INSTANCE加了final关键字,表明初始化1次后不再允许初始化。

懒汉单例设计模式

二、简单懒汉设计模式

由于饿汉模式一开始就初始化好了,但如果一直没有被使用到的话,是会浪费珍贵的内存资源的,所以引出了懒汉模式。

懒汉:首次使用时才会去实例化对象。


public class SingletonLazy1 {
private static SingletonLazy1 instance;

private SingletonLazy1() {
}

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

测试:


public class Main {
public static void main(String[] args) {
SingletonLazy1 instance1 = SingletonLazy1.getInstance();
SingletonLazy1 instance2 = SingletonLazy1.getInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}

测试结果:从结果可以看出,打印出来的两个实例对象地址是一样的,所以认为是只创建了一个对象。

Java单例模式的8种写法(推荐)

三、进阶

1:解决多线程并发问题

上述代码存在的问题:在多线程环境下,不能保证只创建一个实例,我们进行问题的重现:


public class Main {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy1.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy1.getInstance())).start();
}
}

结果:获取到的对象不一样,这并不是我们的预期结果。

Java单例模式的8种写法(推荐)

解决方案:


public class SingletonLazy2 {
private static SingletonLazy2 instance;

private SingletonLazy2() {
}
//在方法加synchronized修饰符
public static synchronized SingletonLazy2 getInstance() {
if (instance == null) {
 instance = new SingletonLazy2();
}
return instance;
}
}

测试:


public class Main2 {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy2.getInstance())).start();
}
}

Java单例模式的8种写法(推荐)

结果:多线程环境下获取到的是同个对象。

四、进阶2:缩小方法锁粒度

上一方案虽然解决了多线程问题,但由于synchronized关键字是加在方法上的,锁粒度很大,当有上万甚至更多的线程同时访问时,都被拦在了方法外,大大降低了程序性能,所以我们要适当缩小锁粒度,控制锁的范围在代码块上。


public class SingletonLazy3 {
private static SingletonLazy3 instance;

private SingletonLazy3() {
}

public static SingletonLazy3 getInstance() {
//代码块1:不要在if外加锁,不然和锁方法没什么区别
if (instance == null) {
 //代码块2:加锁,将方法锁改为锁代码块
 synchronized (SingletonLazy3.class) {
 //代码块3
 instance = new SingletonLazy3();
 }
}
return instance;
}
}

测试:


public class Main3 {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy3.getInstance())).start();
}
}

我们看一下运行结果:还是出现了线程安全的问题(每次执行都可能打印不同的地址情况,只要证明是非线程安全的即可)。

Java单例模式的8种写法(推荐)

原因分析:当线程A拿到锁进入到代码块3并且还没有创建完实例时,线程B是有机会到达代码块2的,此时线程C和D可能在代码块1,当线程A执行完之后释放锁并返回对象1,线程B进入进入代码块3,又创建了新的对象2覆盖对象1并返回,最后当线程C和D在进行判null时发现instance非空,直接返回最后创建的对象2。

五、进阶3:双重检查锁DCL(Double-Checked-Locking)

所谓双重检查锁,就是在线程获取到锁之后再对实例进行第2次判空检查,判断是不是有上一个线程已经进行了实例化,有的话直接返回即可,否则进行实例初始化。


public class SingletonLazy4DCL {
private static SingletonLazy4DCL instance;

private SingletonLazy4DCL() {
}

public static SingletonLazy4DCL getInstance() {
//代码块1:第一次判空检查
if (instance == null) {
 //代码块2:加锁,将方法锁改为锁代码块
 synchronized (SingletonLazy3.class) {
 //代码块3:进行第二次(双重)判空检查
 if (instance == null) {
  instance = new SingletonLazy4DCL();
 }
 }
}
return instance;
}
}

测试:


public class Main4DCL {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy4DCL.getInstance())).start();
}
}

Java单例模式的8种写法(推荐)

六、进阶4:禁止指令重排

在对象的实例过程中,大概可分为以下3个步骤:

  1. 分配对象内存空间

  2. 在空间中创建对象

  3. 实例指向分配到的内存空间地址

由于实例化对象的过程不是原子性的,且JVM本身对Java代码指令有重排的操作,可能1-2-3的操作被重新排序成了1-3-2,这样就会导致在3执行完之后还没来得及创建对象时,其他线程先读取到了未初始化的对象instance并提前返回,在使用的时候会出现NPE空指针异常。

解决:给instance加volatile关键字表明禁止指令重排,出现的概率不大, 但这是更安全的一种做法。


public class SingletonLazy5Volatile {
//加volatile关键字
private volatile static SingletonLazy5Volatile instance;

private SingletonLazy5Volatile() {
}

public static SingletonLazy5Volatile getInstance() {
//代码块1
if (instance == null) {
 //代码块2:加锁,将方法锁改为锁代码块
 synchronized (SingletonLazy3.class) {
 //代码块3
 if (instance == null) {
  instance = new SingletonLazy5Volatile();
 }
 }
}
return instance;
}
}

七、进阶5:静态内部类

我们还可以使用静态类的静态变量被第一次访问时才会进行初始化的特性来进行懒加载初始化。把外部类的单例对象放到静态内部类的静态成员变量里进行初始化。


public class SingletonLazy6InnerStaticClass {
private SingletonLazy6InnerStaticClass() {
}

public static SingletonLazy6InnerStaticClass getInstance() {
return SingletonLazy6InnerStaticClass.InnerStaticClass.instance;
//或者写成return InnerStaticClass.instance;
}

private static class InnerStaticClass {
private static final SingletonLazy6InnerStaticClass instance = new SingletonLazy6InnerStaticClass();
}
}

虽然静态内部类里的写法和饿汉模式很像,但它却不是在外部类加载时就初始化了,而是在第一次被访问到时才会进行初始化的操作(即getInstance方法被调用时),也就起到了懒加载的效果,并且它可以保证线程安全。

测试:


public class Main6InnerStatic {
public static void main(String[] args) {
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
new Thread(()-> System.out.println(SingletonLazy6InnerStaticClass.getInstance())).start();
}
}

Java单例模式的8种写法(推荐)

反射攻击

虽然我们一开始都对构造器进行了私有化处理,但Java本身的反射机制却还是可以将private访问权限改为可访问,依旧可以创建出新的实例对象,这里以饿汉模式举例说明:


public class MainReflectAttack {
public static void main(String[] args) {
try {
 SingletonHungry normal1 = SingletonHungry.getInstance();
 SingletonHungry normal2 = SingletonHungry.getInstance();
 //开始反射创建实例
 Constructor<SingletonHungry> reflect = SingletonHungry.class.getDeclaredConstructor(null);
 reflect.setAccessible(true);
 SingletonHungry attack = reflect.newInstance();

System.out.println("正常静态方法调用获取到的对象:");
 System.out.println(normal1);
 System.out.println(normal2);
 System.out.println("反射获取到的对象:");
 System.out.println(attack);
} catch (Exception e) {
 e.printStackTrace();
}
}
}

Java单例模式的8种写法(推荐)

八、枚举单例(推荐使用)


public enum SingletonEnum {
INSTANCE;
}

枚举是最简洁、线程安全、不会被反射创建实例的单例实现,《Effective Java》中也表明了这种写法是最佳的单例实现模式。

单元素的枚举类型经常成为实现Singleton的最佳方法。 --《Effective Java》

为什么说不会被反射创建对象呢?查阅构造器反射实例化对象方法newInstance的源码可知:反射禁止了枚举对象的实例化,也就防止了反射攻击,不用自己在构造器实现复杂的重复实例化逻辑了。

Java单例模式的8种写法(推荐)

测试:


public class MainEnum {
public static void main(String[] args) {
SingletonEnum instance1 = SingletonEnum.INSTANCE;
SingletonEnum instance2 = SingletonEnum.INSTANCE;
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());
}
}

Java单例模式的8种写法(推荐)

总结:几种实现方式的优缺点 懒汉模式

优点:节省内存。

缺点:存在线程安全问题,若要保证线程安全,则写法复杂。

饿汉模式

优点:线程安全。

缺点:如果单例对象一直没被使用,则会浪费内存空间。

静态内部类

优点:懒加载并避免了多线程问题,写法相比于懒汉模式更简单。

缺点:需要多创建一个内部类。

枚举

优点:简洁、天生线程安全、不可反射创建实例。

缺点:暂无

来源:https://blog.csdn.net/weixin_38582659/article/details/112759822

标签:Java,单例模式
0
投稿

猜你喜欢

  • Android开发之设置开机自动启动的几种方法

    2021-12-04 20:35:37
  • Java利用反射对list对象做过滤

    2023-12-23 07:39:17
  • Java优先队列(PriorityQueue)重写compare操作

    2022-10-02 03:59:12
  • Java经典面试题最全汇总208道(五)

    2023-11-10 07:06:46
  • Android利用传感器实现微信摇一摇功能

    2023-07-12 05:05:18
  • 详解C#中HashTable的用法

    2023-07-17 04:42:07
  • C# Winform 子窗体访问父级窗体的控件和属性

    2022-08-15 04:37:06
  • Springboot集成RabbitMQ死信队列的实现

    2022-08-24 13:10:54
  • java的接口解耦方式

    2023-04-17 00:36:45
  • Java线程的生命周期的详解

    2022-05-18 00:32:08
  • C#实现带阴历显示的日期代码

    2023-12-11 02:19:04
  • spring mvc实现文件上传并携带其他参数的示例

    2023-11-20 11:54:06
  • Java压缩文件ZIP实例代码

    2022-03-25 04:08:27
  • C#使用Dispose模式实现手动对资源的释放

    2022-09-21 16:12:14
  • Android Activity跳转动画效果

    2023-11-25 02:34:51
  • C#中foreach语句使用break暂停遍历的方法

    2022-10-12 20:14:11
  • 改进c# 代码的五个技巧(一)

    2021-07-17 23:49:30
  • 详解SpringBoot工程的三种搭建方式

    2022-09-20 21:47:23
  • 浅析Java的Hibernate框架中的继承关系设计

    2021-10-18 03:10:03
  • springboot乱码问题解决方案

    2022-03-22 21:32:38
  • asp之家 软件编程 m.aspxhome.com