spring单例bean实现原理

Spring 默认实例bean都是单例的  其中单例的实现原理:

定义一个final的ConcurrentHashMap对象,从而该域是线程安全的

privatefinal Map<String, Object> singletonObjectsnew ConcurrentHashMap<String, Object>(64);

其中获取单例的代码放置在同步块中,

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);

 

}

 

获取ClassLoader :Thread.currentThread().getContextClassLoader();

猜你喜欢

转载自568025297.iteye.com/blog/2228586