上一篇主要讲接口SingletonBeanRegistry,本篇主要讲述DefaultSingletonBeanRegistry,DefaultSingletonBeanRegistry主要对接口SingletonBeanRegistry各函数的实现,具体代码如下:
/**DefaultSingletonBeanRegistry 实现了SingletonBeanRegistry ,主要用来管理单例对象,同时继承了 SimpleAliasRegistry ,具有注册别名的作用
*/
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
//内部标记一个空对象,并发maps不支持null
protected static final Object NULL_OBJECT = new Object();
//用来记录日志
protected final Log logger = LogFactory.getLog(getClass());
//用来存放singleton对象的缓存
private final Map singletonObjects = new ConcurrentHashMap(64);
//用来存放生产singleton对象的工厂的缓存
private final Map> singletonFactories = new HashMap>(16);
//用来存放早期的singleton对象的缓存
private final Map earlySingletonObjects = new HashMap(16);
//已经创建好的单例注册表,包括存放顺序
private final Set registeredSingletons = new LinkedHashSet(64);
//正在创建的单例对象的名称
private final Set singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap(16));
//目前正在从创建检查中移除的bean的name列表
private final Set inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap(16));
//存放异常信息
private Set suppressedExceptions;
//当前是否有singleton被销毁
private boolean singletonsCurrentlyInDestruction = false;
//一次性使用的单例对象缓存
private final Map disposableBeans = new LinkedHashMap();
//外部bean与被包含在外部bean的所有内部bean集合包含关系的缓存
private final Map> containedBeanMap = new ConcurrentHashMap>(16);
//指定bean与依赖指定bean的所有bean的依赖关系的缓存
private final Map> dependentBeanMap = new ConcurrentHashMap>(64);
//指定bean与创建这个bean所需要依赖的所有bean的依赖关系的缓存
private final Map> dependenciesForBeanMap = new ConcurrentHashMap>(64);
//注册单例对象
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
//beanName不能为空
Assert.notNull(beanName, "'beanName' 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) {
//如果单例对象为空则注册为一个空对象非null因为ConcurrentHashMap不支持null
this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
// beanName已被注册存放在singletonObjects缓存,那么singletonFactories不应该再持有名称为beanName的工厂
this.singletonFactories.remove(beanName);
//同什么一样earlySingletonObjects不应该再持有名称为beanName的bean
this.earlySingletonObjects.remove(beanName);
//在单例注册表中加入相应的beanName
this.registeredSingletons.add(beanName);
}
}
//添加beanName对应的factory
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
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
//获取淡定对象的地方
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//首先去单例对象缓冲中获取
Object singletonObject = this.singletonObjects.get(beanName);
//如果存在则直接返回
//不存在或者为空判断是否正在创建
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//加上同步块,防止并发操作
synchronized (this.singletonObjects) {
//从早期的单例缓存中获取
//在注册成功之前,early singleton和beanFactory已经初始化好
//如果不存在说明正处在工厂创建阶段
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//从工厂缓存中去对应的工厂
ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//工厂存在则直接从工厂中获取单例对象
singletonObject = singletonFactory.getObject();
//同时将单例对象添加到未注册的earlySingleton缓存中方便注册
this.earlySingletonObjects.put(beanName, singletonObject);
//移除工厂中的单例名称
this.singletonFactories.remove(beanName);
}
}
}
}
//如果对象为空对象则返回null
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
//从工厂中获取单例对象
public Object getSingleton(String beanName, ObjectFactory> singletonFactory) {
//参数校验
Assert.notNull(beanName, "'beanName' must not be null");
//加锁防止并发操作
synchronized (this.singletonObjects) {
//从单例对象缓存中获取
Object singletonObject = this.singletonObjects.get(beanName);
//如果对象为空则报错
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while the 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 {
//从工厂中获取对象
singletonObject = singletonFactory.getObject();
//同时直接注册单例对象
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
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);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
//添加异常信息
protected void onSuppressedException(Exception ex) {
synchronized (this.singletonObjects) {
if (this.suppressedExceptions != null) {
this.suppressedExceptions.add(ex);
}
}
}
//移除名称为beanName的单例
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();
}
}
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);
}
//判断单例对象是否正在创建
public boolean isSingletonCurrentlyInCreation(String beanName) {
return this.singletonsCurrentlyInCreation.contains(beanName);
}
//判断是否正在创建,如果未正在创建则报错
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
//判断是否创建成功,如果没成功则报错
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
//将一次性的单例对象添加到一次性单例对象缓存中
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
//注册两个bean之间的一个包含关系
public void registerContainedBean(String containedBeanName, String containingBeanName) {
// A quick check for an existing entry upfront, avoiding synchronization...
Set containedBeans = this.containedBeanMap.get(containingBeanName);
if (containedBeans != null && containedBeans.contains(containedBeanName)) {
return;
}
// No entry yet -> fully synchronized manipulation of the containedBeans Set
synchronized (this.containedBeanMap) {
containedBeans = this.containedBeanMap.get(containingBeanName);
if (containedBeans == null) {
containedBeans = new LinkedHashSet(8);
this.containedBeanMap.put(containingBeanName, containedBeans);
}
containedBeans.add(containedBeanName);
}
registerDependentBean(containedBeanName, containingBeanName);
}
//注册给定bean的一个依赖bean,给定的bean销毁之前被销毁
public void registerDependentBean(String beanName, String dependentBeanName) {
// A quick check for an existing entry upfront, avoiding synchronization...
String canonicalName = canonicalName(beanName);
Set dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans != null && dependentBeans.contains(dependentBeanName)) {
return;
}
// No entry yet -> fully synchronized manipulation of the dependentBeans Set
synchronized (this.dependentBeanMap) {
dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans == null) {
dependentBeans = new LinkedHashSet(8);
this.dependentBeanMap.put(canonicalName, dependentBeans);
}
dependentBeans.add(dependentBeanName);
}
synchronized (this.dependenciesForBeanMap) {
Set dependenciesForBean = this.dependenciesForBeanMap.get(dependentBeanName);
if (dependenciesForBean == null) {
dependenciesForBean = new LinkedHashSet(8);
this.dependenciesForBeanMap.put(dependentBeanName, dependenciesForBean);
}
dependenciesForBean.add(canonicalName);
}
}
//判断beanName是否依赖dependentBeanName
protected boolean isDependent(String beanName, String dependentBeanName) {
String canonicalName = canonicalName(beanName);
Set dependentBeans = this.dependentBeanMap.get(canonicalName);
if (dependentBeans == null) {
return false;
}
if (dependentBeans.contains(dependentBeanName)) {
return true;
}
for (String transitiveDependency : dependentBeans) {
if (isDependent(transitiveDependency, dependentBeanName)) {
return true;
}
}
return false;
}
//判断beanName是否有依赖的bean
protected boolean hasDependentBean(String beanName) {
return this.dependentBeanMap.containsKey(beanName);
}
//返回依赖于指定的bean的所有bean的名称,如果有的话。
public String[] getDependentBeans(String beanName) {
Set dependentBeans = this.dependentBeanMap.get(beanName);
if (dependentBeans == null) {
return new String[0];
}
return StringUtils.toStringArray(dependentBeans);
}
//获取beanName所有依赖的bean
public String[] getDependenciesForBean(String beanName) {
Set dependenciesForBean = this.dependenciesForBeanMap.get(beanName);
if (dependenciesForBean == null) {
return new String[0];
}
return dependenciesForBean.toArray(new String[dependenciesForBean.size()]);
}
//销毁单例对象
public void destroySingletons() {
if (logger.isDebugEnabled()) {
logger.debug("Destroying singletons in " + this);
}
synchronized (this.singletonObjects) {
this.singletonsCurrentlyInDestruction = true;
}
String[] disposableBeanNames;
synchronized (this.disposableBeans) {
disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
}
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
synchronized (this.singletonObjects) {
this.singletonObjects.clear();
this.singletonFactories.clear();
this.earlySingletonObjects.clear();
this.registeredSingletons.clear();
this.singletonsCurrentlyInDestruction = false;
}
}
//销毁指定beanName的对象
public void destroySingleton(String beanName) {
// Remove a registered singleton of the given name, if any.
removeSingleton(beanName);
// Destroy the corresponding DisposableBean instance.
DisposableBean disposableBean;
synchronized (this.disposableBeans) {
disposableBean = (DisposableBean) this.disposableBeans.remove(beanName);
}
destroyBean(beanName, disposableBean);
}
//销毁指定beanName的对象
protected void destroyBean(String beanName, DisposableBean bean) {
// Trigger destruction of dependent beans first...
Set dependencies = this.dependentBeanMap.remove(beanName);
if (dependencies != null) {
if (logger.isDebugEnabled()) {
logger.debug("Retrieved dependent beans for bean '" + beanName + "': " + dependencies);
}
for (String dependentBeanName : dependencies) {
destroySingleton(dependentBeanName);
}
}
// Actually destroy the bean now...
if (bean != null) {
try {
bean.destroy();
}
catch (Throwable ex) {
logger.error("Destroy method on bean with name '" + beanName + "' threw an exception", ex);
}
}
// Trigger destruction of contained beans...
Set containedBeans = this.containedBeanMap.remove(beanName);
if (containedBeans != null) {
for (String containedBeanName : containedBeans) {
destroySingleton(containedBeanName);
}
}
// Remove destroyed bean from other beans' dependencies.
synchronized (this.dependentBeanMap) {
for (Iterator>> it = this.dependentBeanMap.entrySet().iterator(); it.hasNext();) {
Map.Entry> entry = it.next();
Set dependenciesToClean = entry.getValue();
dependenciesToClean.remove(beanName);
if (dependenciesToClean.isEmpty()) {
it.remove();
}
}
}
// Remove destroyed bean's prepared dependency information.
this.dependenciesForBeanMap.remove(beanName);
}
/**
* Expose the singleton mutex to subclasses.
* Subclasses should synchronize on the given Object if they perform
* any sort of extended singleton creation phase. In particular, subclasses
* should not have their own mutexes involved in singleton creation,
* to avoid the potential for deadlocks in lazy-init situations.
*/
protected final Object getSingletonMutex() {
return this.singletonObjects;
}
}