单例模式-双重检验锁

2019-01-10  本文已影响0人  归去来ming

代码如下:

public class Singleton{

    private Singleton(){};             //私有化构造方法

    private static volatile Singleton = null;

    public static SingletongetInstance(){

   //第一次校验

   if(Singleton==null){

       synchronized(Singleton.class){

           //第二次校验

          if(Singleton==null){

              Singleton=new Singleton();

           }

       }

    }

    return Singleton;

}

在Spring中有用到这个单例模式,Spring依赖注入Bean实例默认是单例的。在AbstractBeanFactory的getBean里。getBean的doGetBean方法调用getSingleton进行bean的创建。

/**

    * Return the (raw) singleton object registered under the given name.

    * <p>Checks already instantiated singletons and also allows for an early

    * reference to a currently created singleton (resolving a circular reference).

    * @param beanName the name of the bean to look for

    * @param allowEarlyReference whether early references should be created or not

    * @return the registered singleton object, or {@code null} if none found

    */

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

    }

上一篇 下一篇

猜你喜欢

热点阅读