标签:incr 单例对象 无法 name 解决 核心 理解 OLE prot
之前面试有被问到过,面试官很调皮,我擅长的点没有问,然后抽了一个点让我回答,这个点考察了源码的理解,当时只是大概记得是提前暴露,但是细节答得有些粗糙,特补充一下,,,
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); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return (singletonObject != NULL_OBJECT ? singletonObject : null); }
解决循环依赖的核心代码如上,首先会从singletonObjects缓存中取对象,如果对象不存在,但处于创建中,则加锁缓存,然后从提前暴露单例缓存中去拿对象,仍然无法取到则查看是否允许提前引用,如果允许,则从单例工厂缓存中获取单例工厂,然后从工厂中获取单例对象,然后将单例工厂从工厂缓存中移除。
标签:incr 单例对象 无法 name 解决 核心 理解 OLE prot
原文地址:https://www.cnblogs.com/lxk2010012997/p/11219697.html