美文网首页
单例模式-双重检验锁

单例模式-双重检验锁

作者: 归去来ming | 来源:发表于2019-01-10 09:05 被阅读0次

    代码如下:

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

        }

    相关文章

      网友评论

          本文标题:单例模式-双重检验锁

          本文链接:https://www.haomeiwen.com/subject/mirorqtx.html