spring三级缓存为什么不可以去掉第二级

1,492 阅读1分钟

原因:因为大多数情况 singletonFactory.getObject()都是返回的一个新对象(相当于直接new对象),如果不加第二级缓存则不能保证单例。

如果强行去掉第二级缓存,只要第一级和第三级缓存行不行呢?

答:可以,但会增加实现的复杂度。例:singletonFactory.getObject()获取的未初始化单例可以放到一级缓存,但是别的对象获取到未初始化的对象,可以考虑添加前缀解决。

解释:如下

spring获取单例的方法, singletonObjects(一级缓存:存放完全体单例) earlySingletonObjects(二级缓存:存放初始化但没有赋值的单例) singletonFactory(三级缓存:初始化后没有赋值的单例用ObjectFactory包装的对象,其实所有的单例实例化后都会放入此缓存;)

注:获取第三级缓存并不是直接从map里get值,如果是普通单例则 ObjectFactory.getObject直接返回自己本身;如果是实现了FactoryBean接口,ObjectFactory.getObject返回的是自己写的重载方法

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
   // Quick check for existing instance without full singleton lock
   Object singletonObject = this.singletonObjects.get(beanName);
   if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
      singletonObject = this.earlySingletonObjects.get(beanName);
      if (singletonObject == null && allowEarlyReference) {
         synchronized (this.singletonObjects) {
            // Consistent creation of early reference within full singleton lock
            singletonObject = this.singletonObjects.get(beanName);
            if (singletonObject == null) {
               singletonObject = this.earlySingletonObjects.get(beanName);
               if (singletonObject == null) {
                  ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                  if (singletonFactory != null) {
                     //第三级缓存要调用singletonFactory.getObject()方法
                     singletonObject = singletonFactory.getObject();
                     this.earlySingletonObjects.put(beanName, singletonObject);
                     this.singletonFactories.remove(beanName);
                  }
               }
            }
         }
      }
   }
   return singletonObject;
}