Spring三级缓存源码

文章目录

Spring三级缓存类源码分析

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry { 

    // 1级缓存:存放实例化+属性注入+初始化+代理(如果有代理)后的单例bean
    private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
    // 2级缓存:存放实例化+代理(如果有代理)后的单例bean
    private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
    // 3级缓存:存放封装了单例bean(实例化的)的对象工厂
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
    // 已经完成注册的单例beanName
    private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
    // 正在创建中的beanName
    private final Set<String> singletonsCurrentlyInCreation =  Collections.newSetFromMap(new ConcurrentHashMap<>(16));
    // 当前不检查的bean的集合
    private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
    // 存放异常出现的相关的原因的集合
    private Set<Exception> suppressedExceptions;
    // 标志,目前是否在销毁单例中
    private boolean singletonsCurrentlyInDestruction = false;
    // 存放一次性bean的缓存
    private final Map<String, Object> disposableBeans = new LinkedHashMap<>();
    // 外部bean与被包含在外部bean的所有内部bean集合包含关系的缓存
    private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<>(16);
    // 指定bean与依赖指定bean的所有bean的依赖关系的缓存
    private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<>(64);
    // 指定bean与创建这个bean所需要依赖的所有bean的依赖关系的缓存
    private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<>(64);

    /** * 注册单例对象到一级缓存(若一级缓存中已存在则抛出异常) */
    @Override
    public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { 
        Assert.notNull(beanName, "Bean name must not be null");
        Assert.notNull(singletonObject, "Singleton object must not be null");
        synchronized (this.singletonObjects) { 
            Object oldObject = this.singletonObjects.get(beanName);
            // 如果一级缓存有,说明已经注册过
            if (oldObject != null) { 
                throw new IllegalStateException("Could not register object [" + singletonObject +
                        "] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
            }
            // 一级缓存没有,开始注册
            addSingleton(beanName, singletonObject);
        }
    }

    /** * 添加到一级缓存(并移除二级、三级缓存) */
    protected void addSingleton(String beanName, Object singletonObject) { 
        synchronized (this.singletonObjects) { 
            // 加入单例对象到一级缓存
            this.singletonObjects.put(beanName, singletonObject);
            // 删除三级缓存
            this.singletonFactories.remove(beanName);
            // 删除二级缓存
            this.earlySingletonObjects.remove(beanName);
            // 加入已注册的bean
            this.registeredSingletons.add(beanName);
        }
    }

    /** * 添加到三级级缓存 */
    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) { 
        Assert.notNull(singletonFactory, "Singleton factory must not be null");
        synchronized (this.singletonObjects) { 
            // 如果一级缓存没有,添加对象工厂到三级缓存
            if (!this.singletonObjects.containsKey(beanName)) { 
                this.singletonFactories.put(beanName, singletonFactory);
                this.earlySingletonObjects.remove(beanName);
                this.registeredSingletons.add(beanName);
            }
        }
    }

    /** * 获取单例 */
    @Override
    @Nullable
    public Object getSingleton(String beanName) { 
        // 允许早期依赖
        return getSingleton(beanName, true);
    }

    /** * 获取单例 * 2.如果二级缓存有直接返回 * 3.如果三级缓存有,通过singletonFactory.getObject()的到未完成的单例对象,并移除三级缓存,返回未完成的单例对象 * @param allowEarlyReference true:允许早期依赖 * @return */
    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) { 
        // 如果一级缓存有,直接返回
        Object singletonObject = this.singletonObjects.get(beanName);
        // 如果一级缓存没有,但正在创建
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { 
            synchronized (this.singletonObjects) { 
                // 如果二级缓存中有,说明正在加载,则直接返回
                singletonObject = this.earlySingletonObjects.get(beanName);
                // 二级缓存也没有,且允许早期依赖
                if (singletonObject == null && allowEarlyReference) { 
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    // 三级缓存有,调用getObject方法创建bean并放入到二级缓存,并删除三级缓存
                    if (singletonFactory != null) { 
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }

    /** * 获取单例 */
    public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) { 
        Assert.notNull(beanName, "Bean name must not be null");
        synchronized (this.singletonObjects) { 
            // 一级缓存有,直接返回
            Object singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) { 
                // 当前正在销毁bean,不能创建
                if (this.singletonsCurrentlyInDestruction) { 
                    throw new BeanCreationNotAllowedException(beanName,
                            "Singleton bean creation not allowed while singletons of this factory are in destruction " +
                                    "(Do not request a bean from a BeanFactory in a destroy method implementation!)");
                }
                if (logger.isDebugEnabled()) { 
                    logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
                }
                // 创建前检查,记录正在加载状态
                beforeSingletonCreation(beanName);
                boolean newSingleton = false;
                // 如果当前没有异常,初始化异常集合
                boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
                if (recordSuppressedExceptions) { 
                    this.suppressedExceptions = new LinkedHashSet<>();
                }
                try { 
                    // 调用getObject方法创建bean
                    singletonObject = singletonFactory.getObject();
                    newSingleton = true;
                }
                catch (IllegalStateException ex) { 
                    // 有可能是其他方式创建的bean
                    singletonObject = this.singletonObjects.get(beanName);
                    if (singletonObject == null) { 
                        throw ex;
                    }
                }
                catch (BeanCreationException ex) { 
                    if (recordSuppressedExceptions) { 
                        for (Exception suppressedException : this.suppressedExceptions) { 
                            ex.addRelatedCause(suppressedException);
                        }
                    }
                    throw ex;
                }
                finally { 
                    if (recordSuppressedExceptions) { 
                        this.suppressedExceptions = null;
                    }
                    // 创建后检查,移除加载状态
                    afterSingletonCreation(beanName);
                }
                // 如果是新创建的bean,添加到一级缓存(并移除二级、三级缓存)
                if (newSingleton) { 
                    addSingleton(beanName, singletonObject);
                }
            }
            return singletonObject;
        }
    }

    /** * 注册过程中发生的异常,加入到异常集合 */
    protected void onSuppressedException(Exception ex) { 
        synchronized (this.singletonObjects) { 
            if (this.suppressedExceptions != null) { 
                this.suppressedExceptions.add(ex);
            }
        }
    }

    /** * 移除单例,这四个缓存同时移除 */
    protected void removeSingleton(String beanName) { 
        synchronized (this.singletonObjects) { 
            this.singletonObjects.remove(beanName);
            this.singletonFactories.remove(beanName);
            this.earlySingletonObjects.remove(beanName);
            this.registeredSingletons.remove(beanName);
        }
    }

    /** * 单例是否一存在 */
    @Override
    public boolean containsSingleton(String beanName) { 
        return this.singletonObjects.containsKey(beanName);
    }

    /** * 已注册的单例名称集合 */
    @Override
    public String[] getSingletonNames() { 
        synchronized (this.singletonObjects) { 
            return StringUtils.toStringArray(this.registeredSingletons);
        }
    }

    /** * 已注册的单例名称数量 */
    @Override
    public int getSingletonCount() { 
        synchronized (this.singletonObjects) { 
            return this.registeredSingletons.size();
        }
    }


    /** * 设置不检查的beanName */
    public void setCurrentlyInCreation(String beanName, boolean inCreation) { 
        Assert.notNull(beanName, "Bean name must not be null");
        if (!inCreation) { 
            this.inCreationCheckExclusions.add(beanName);
        }
        else { 
            this.inCreationCheckExclusions.remove(beanName);
        }
    }

    public boolean isCurrentlyInCreation(String beanName) { 
        Assert.notNull(beanName, "Bean name must not be null");
        return (!this.inCreationCheckExclusions.contains(beanName) && isActuallyInCreation(beanName));
    }

    protected boolean isActuallyInCreation(String beanName) { 
        return isSingletonCurrentlyInCreation(beanName);
    }

    /** * 是否当前创建的bean */
    public boolean isSingletonCurrentlyInCreation(String beanName) { 
        return this.singletonsCurrentlyInCreation.contains(beanName);
    }

    /** * 创建前检查,记录正在加载状态 */
    protected void beforeSingletonCreation(String beanName) { 
        // 如果这个beanName要检查,记录创建状态。如果返回false,说明已经正在创建了,抛异常
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) { 
            throw new BeanCurrentlyInCreationException(beanName);
        }
    }

    /** * 创建后检查,移除加载状态 */
    protected void afterSingletonCreation(String beanName) { 
        // 如果这个beanName要检查,移除创建状态。如果返回false,说明已经创建完了。抛异常
        if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) { 
            throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
        }
    }


    /** * 注册一次性bean实例 */
    public void registerDisposableBean(String beanName, DisposableBean bean) { 
        synchronized (this.disposableBeans) { 
            this.disposableBeans.put(beanName, bean);
        }
    }

    /** * 注册包含的bean */
    public void registerContainedBean(String containedBeanName, String containingBeanName) { 
        synchronized (this.containedBeanMap) { 
            // 如果没有key为containingBeanName的value,说明内部bean集合为空,则初始化一个
            Set<String> containedBeans = this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
            // 如果已经存在了对应关系,则直接返回
            if (!containedBeans.add(containedBeanName)) { 
                return;
            }
        }
        // 不存在了对应关系,添加对应关系
        registerDependentBean(containedBeanName, containingBeanName);
    }

    /** * 注册依赖的bean */
    public void registerDependentBean(String beanName, String dependentBeanName) { 
        String canonicalName = canonicalName(beanName);

        synchronized (this.dependentBeanMap) { 
            Set<String> dependentBeans = this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
            // 如果已经存在了对应关系,则直接返回
            if (!dependentBeans.add(dependentBeanName)) { 
                return;
            }
        }
        // 不经存在了对应关系,添加对应关系
        synchronized (this.dependenciesForBeanMap) { 
            Set<String> dependenciesForBean = this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
            dependenciesForBean.add(canonicalName);
        }
    }

    /** * dependentBeanName是否依赖beanName */
    protected boolean isDependent(String beanName, String dependentBeanName) { 
        synchronized (this.dependentBeanMap) { 
            return isDependent(beanName, dependentBeanName, null);
        }
    }

    /** * dependentBeanName是否依赖beanName */
    private boolean isDependent(String beanName, String dependentBeanName, @Nullable Set<String> alreadySeen) { 
        if (alreadySeen != null && alreadySeen.contains(beanName)) { 
            return false;
        }
        String canonicalName = canonicalName(beanName);
        Set<String> dependentBeans = this.dependentBeanMap.get(canonicalName);
        // bean依赖beanName,直接返回false
        if (dependentBeans == null) { 
            return false;
        }
        // 有其他bean依赖beanName,且包含了dependentBeanName,返回true
        if (dependentBeans.contains(dependentBeanName)) { 
            return true;
        }
        // 有其他bean依赖beanName,但是不包含dependentBeanName
        for (String transitiveDependency : dependentBeans) { 
            if (alreadySeen == null) { 
                alreadySeen = new HashSet<>();
            }
            alreadySeen.add(beanName);
            // 是否有循环依赖
            if (isDependent(transitiveDependency, dependentBeanName, alreadySeen)) { 
                return true;
            }
        }
        return false;
    }

    /** * 是否有其他对象依赖指定bean */
    protected boolean hasDependentBean(String beanName) { 
        return this.dependentBeanMap.containsKey(beanName);
    }

    /** * 返回依赖指定bean的数组 */
    public String[] getDependentBeans(String beanName) { 
        Set<String> dependentBeans = this.dependentBeanMap.get(beanName);
        if (dependentBeans == null) { 
            return new String[0];
        }
        synchronized (this.dependentBeanMap) { 
            return StringUtils.toStringArray(dependentBeans);
        }
    }

    /** * 返回指定bean,依赖其他bean的数组 */
    public String[] getDependenciesForBean(String beanName) { 
        Set<String> dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
        if (dependenciesForBean == null) { 
            return new String[0];
        }
        synchronized (this.dependenciesForBeanMap) { 
            return StringUtils.toStringArray(dependenciesForBean);
        }
    }

    /** * 销毁所有单例 */
    public void destroySingletons() { 
        if (logger.isTraceEnabled()) { 
            logger.trace("Destroying singletons in " + this);
        }
        // 设置当前正在销毁
        synchronized (this.singletonObjects) { 
            this.singletonsCurrentlyInDestruction = true;
        }

        String[] disposableBeanNames;
        synchronized (this.disposableBeans) { 
            disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
        }
        // 销毁disposableBeans中的所有bean
        for (int i = disposableBeanNames.length - 1; i >= 0; i--) { 
            destroySingleton(disposableBeanNames[i]);
        }
        // 清空containedBeanMap、dependentBeanMap、dependenciesForBeanMap
        this.containedBeanMap.clear();
        this.dependentBeanMap.clear();
        this.dependenciesForBeanMap.clear();
        // 清除所有单例缓存
        clearSingletonCache();
    }

    /** * 清除所有单例缓存 */
    protected void clearSingletonCache() { 
        synchronized (this.singletonObjects) { 
            // 清除所有单例缓存
            this.singletonObjects.clear();
            this.singletonFactories.clear();
            this.earlySingletonObjects.clear();
            this.registeredSingletons.clear();
            // 清除完后,标志恢复为false
            this.singletonsCurrentlyInDestruction = false;
        }
    }

    /** * 销毁单例bean */
    public void destroySingleton(String beanName) { 
        // 从缓存中移除
        removeSingleton(beanName);
        // 从disposableBeans移除,如果有beanName对应的对象,返回这个对象
        DisposableBean disposableBean;
        synchronized (this.disposableBeans) { 
            disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
        }
        // 销毁bean
        destroyBean(beanName, disposableBean);
    }

    /** * 销毁bean */
    protected void destroyBean(String beanName, @Nullable DisposableBean bean) { 
        // 获取依赖当前beanName的bean
        Set<String> dependencies;
        synchronized (this.dependentBeanMap) { 
            dependencies = this.dependentBeanMap.remove(beanName);
        }
        // 移除依赖当前beanName的bean
        if (dependencies != null) { 
            if (logger.isTraceEnabled()) { 
                logger.trace("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
            }
            for (String dependentBeanName : dependencies) { 
                destroySingleton(dependentBeanName);
            }
        }
        if (bean != null) { 
            try { 
                bean.destroy();
            }
            catch (Throwable ex) { 
                if (logger.isWarnEnabled()) { 
                    logger.warn("Destruction of bean with name '" + beanName + "' threw an exception", ex);
                }
            }
        }
        // 移除beanName的对应关系的bean
        Set<String> containedBeans;
        synchronized (this.containedBeanMap) { 
            // Within full synchronization in order to guarantee a disconnected Set
            containedBeans = this.containedBeanMap.remove(beanName);
        }
        if (containedBeans != null) { 
            for (String containedBeanName : containedBeans) { 
                destroySingleton(containedBeanName);
            }
        }
        // 这个对象被其他bean依赖,也要移除依赖关系
        synchronized (this.dependentBeanMap) { 
            for (Iterator<Map.Entry<String, Set<String>>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) { 
                Map.Entry<String, Set<String>> entry = it.next();
                Set<String> dependenciesToClean = entry.getValue();
                dependenciesToClean.remove(beanName);
                if (dependenciesToClean.isEmpty()) { 
                    it.remove();
                }
            }
        }
        // 移除当前bean与依赖其他bean的关系
        this.dependenciesForBeanMap.remove(beanName);
    }

    /** * 用于加锁操作,返回singletonObjects,通过方法暴露这个对象。 */
    @Override
    public final Object getSingletonMutex() { 
        return this.singletonObjects;
    }
}
    原文作者:骑个小蜗牛
    原文地址: https://blog.csdn.net/JokerLJG/article/details/123753659
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞