【设计模式In Java】二、单例模式

本文深入解析单例模式的定义、应用场景、实现方式及其线程安全问题。通过对比懒加载、饿汉模式及双重检查锁定等不同实现,探讨了最优实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式

定义

单例模式(Singleton Pattern):确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称为单例类,它提供全局访问的方法。单例模式是一种对象创建型模式。

单例模式有三个要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。

场景

准备在网站中添加一个访问计数器,为了保证计数器在程序中唯一,现在需要将计数器设计为单例模式,否则可能出现多个计数器导致计数不正确。

UML类图

在这里插入图片描述

代码

singleton
示例:

public void test() throws InterruptedException {
    ApplicationCounter applicationCounter = ApplicationCounter.getApplicationCounter();
    ApplicationCounter applicationCounter1 = ApplicationCounter.getApplicationCounter();
    assert applicationCounter == applicationCounter1;
    for (int i = 0; i < 100; i++) {
        new Thread(applicationCounter::increase).start();
    }
    Thread.sleep(100L);
    System.out.println(applicationCounter.get());
}

总结

上面的单例实现方式其实是存在线程安全问题的:不考虑并发时,这种使用时先判断是否为空再决定是否初始化(懒加载)确实可以保证对象唯一,但是考虑高并发的时候,就有线程安全问题。

假设有多个线程同时调用getApplicationCounter(),并且都判定为空,那就会初始化多次,这时候有两种解决方案:
第一种是使用饿汉模式,即在声明时就初始化,即类加载时就初始化:

public class ApplicationCounter1 {

    private AtomicInteger counter = new AtomicInteger(0);

    private static ApplicationCounter1 applicationCounter1 = new ApplicationCounter1();

    public synchronized Integer increase(){
        return applicationCounter1.counter.addAndGet(1);
    }

    public Integer get(){
        return applicationCounter1.counter.get();
    }

    public static ApplicationCounter1 getApplicationCounter(){
        return applicationCounter1;
    }

}

这样写的好处是可以确保对象唯一,但坏处也显而易见:假设并不需要使用此对象,对象也会被创建,造成资源浪费,那么依然可以使用原先的方法,并且在getApplicationCounter()方法前加上synchronized不就好了吗:

public class ApplicationCounter2 {

    private AtomicInteger counter = new AtomicInteger(0);

    private static ApplicationCounter2 applicationCounter2;

    public Integer increase(){
        return applicationCounter2.counter.addAndGet(1);
    }

    public Integer get(){
        return applicationCounter2.counter.get();
    }

    public static synchronized ApplicationCounter2 getApplicationCounter(){
        if(applicationCounter2 == null){
            applicationCounter2 = new ApplicationCounter2();
        }

        return applicationCounter2;
    }
    
}

问题得到解决,但是每次获取对象的时候都会加锁,在高并发场景下可能导致性能大大降低,但可以通过减小锁的粒度来优化,因为我们并不需要对整个方法加锁,只需要对if判断加锁即可:

public static ApplicationCounter2 getApplicationCounter(){
    if(applicationCounter2 == null){
        synchronized(ApplicationCounter2.class){
			applicationCounter2 = new ApplicationCounter2();
		}
    }

    return applicationCounter2;
}

问题貌似得到解决,但其实不然,因为可能同时有多个线程进入了if块,那么会有多个线程先后进入同步块,还是会出现初始化多次的情况,那我们可以在同步块内再做一次判断,这样在同步块前做一次判断,进入同步块后再做一次判断的方式称为“双重检查锁定(Double-Check Locking)”:

private volatile static ApplicationCounter2 applicationCounter2;

...

public static ApplicationCounter2 getApplicationCounter(){
    //check1
    if(applicationCounter2 == null){
        synchronized(ApplicationCounter2.class){
            //check2
        	if(applicationCounter2 == null){
        		applicationCounter2 = new ApplicationCounter2();
        	}
		}
    }

    return applicationCounter2;
}

记得用volatile修饰单例对象,可以确保线程之间的可见性和禁止指令重排,一旦对象被初始化,其他线程会立马拿到更新后的值去和null比较,从而防止线程用本地副本和null比较,也就不会导致实例被多次初始化。但这种解决方法不是特别优雅,volatile也会一定程度上降低性能,所以双重检查锁定也不是一个完美的解决方法。

有没有结合懒加载和按需加载两种方式的方法呢?是有的:

public class ApplicationCounter3 {

    private AtomicInteger counter = new AtomicInteger(0);

    private static class ApplicationCounterHolder{
        private final static ApplicationCounter3 applicationCounter3 = new ApplicationCounter3();
    }

    public Integer increase(){
        return ApplicationCounterHolder.applicationCounter3.counter.addAndGet(1);
    }

    public Integer get(){
        return ApplicationCounterHolder.applicationCounter3.counter.get();
    }

    public static synchronized ApplicationCounter3 getApplicationCounter(){
        return ApplicationCounterHolder.applicationCounter3;
    }
    
}

由于静态单例对象没有作为ApplicationCounter3的成员变量直接实例化,因此类加载时不会实例化ApplicationCounter3,第一次调用getApplicationCounter()时将加载内部类ApplicationCounterHolder,在该内部类中定义了一个static类型的变量,此时会首先初始化这个成员变量,由Java虚拟机来保证其线程安全性,确保该成员变量只能初始化一次。由于getApplicationCounter()方法没有任何线程锁定,因此其性能不会造成任何影响。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值