Spring中线程安全的单例模式源码分析

版权声明:本文为博主原创文章,转载时需要带上原文链接。 https://blog.csdn.net/a158123/article/details/86499608

前言

最近学习Spring AOP源码时,看到了Spring源码中十分惊艳的一个线程安全类,所以特意记录下来。

源码

public abstract class GlobalAdvisorAdapterRegistry {

	/**
	 * 利用类变量防止单例对象再次被初始化
	 */
	private static AdvisorAdapterRegistry instance = new DefaultAdvisorAdapterRegistry();

	/**
	 * 返回单例对象
	 */
	public static AdvisorAdapterRegistry getInstance() {
		return instance;
	}

	/**
	 * 重置单例对象
	 */
	static void reset() {
		instance = new DefaultAdvisorAdapterRegistry();
	}

}

分析

分析这段源码前,首先得介绍一下单例模式的实现饿汉式(静态常量),其示例代码如下:

public class Singleton {
	/**
	 * 使用静态常量防止单例对象再次被初始化
	 */
    private final static Singleton INSTANCE = new Singleton();
	/**
	 * 私有化构造方法,防止单例模式被破坏
	 */
    private Singleton(){}
	/**
	 * 类方法获取单例对象
	 */
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

Spring源码中GlobalAdvisorAdapterRegistry则是利用了抽象类的特性,确保GlobalAdvisorAdapterRegistry不会被实例化。

猜你喜欢

转载自blog.csdn.net/a158123/article/details/86499608