dubbo metadata层 深入类加载机制

最近在社区上提交pull request的时候遇到了这个问题

dubbo metadata层 深入类加载机制_第1张图片
problem.png

首先我们来看下Class.forName方法的实现

/**
     * Returns the {@code Class} object associated with the class or
     * interface with the given string name.  Invoking this method is
     * equivalent to:
     * A call to {@code forName("X")} causes the class named
     * {@code X} to be initialized.
     *
     * @param      className   the fully qualified name of the desired class.
     * @return     the {@code Class} object for the class with the
     *             specified name.
     * @exception LinkageError if the linkage fails
     * @exception ExceptionInInitializerError if the initialization provoked
     *            by this method fails
     * @exception ClassNotFoundException if the class cannot be located
     */
    @CallerSensitive
    public static Class forName(String className)
                throws ClassNotFoundException {
        Class caller = Reflection.getCallerClass();
        return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
    }

java的类加载过程是将 java代码编译成字节码,然后用ClassLoader装载class文件

也就是说在我们没有指定类加载器的情况下,他会根据这个类自身的class文件,调用此方法加载的类作为他的classLoader,对这个class文件进行加载

打个比方,比如说Metadata类中有这样一行代码

Class interfaceClass = Class.forName(interfaceName);

那在未指定classLoader的情况下,classLoader就是Metadata.class的ClassLoader。

最初的想法是参考jdbc的isDriverAllowed方法,在加载类的时候做一次类加载器的判断

private static boolean isDriverAllowed(Driver driver, ClassLoader classLoader) {
        boolean result = false;
        if(driver != null) {
            Class aClass = null;
            try {
                //在之前分析知道,在com.mysql.jdbc.Driver初始化的时候,调用了DriverManager的注册方法,
                //会加载java.sql.Driver的实现到DriverManager里边的registeredDrivers集合中; 
                //在这里又进行了一次加载,但是不同的是进行了初始化。
                aClass =  Class.forName(driver.getClass().getName(), true, classLoader);
            } catch (Exception ex) {
                result = false;
            }
            //这行代码是核心,为什么要进行一次"=="判断呢,这主要是为了避免类加载命名空间的问题,即aClass 和 driver.getClass()是由同一个类加载器加载的,
            //不同的加载器可能出现的情况是程序里边使用线程上下文加载器设置的加载器去加载(比如设置了用户自定义的加载器),和原始的加载器命名空间不一样。
            //之前的文章介绍过,也举过例子,即便是2个名字完全一样的类,由于类加载器不一样后边使用的时候一定会出现CastException
             result = ( aClass == driver.getClass() ) ? true : false;
        }

        return result;
    }

但我们这里的类的类型已经是确定的,在同一个请求中一个线程调用的classLoader都是相同的,所以就要考虑用线程的上下文加载器Thread.currentThread().getContextClassLoader

每当一个线程调用,根据方法的调用产生的栈帧按顺序调用时,就组成了线程栈,这个过程中线程加载的class文件也在不断更新。

这位用户提到的不同的类加载器加载class文件,根据dubbo内提供的getClass方法,可能是这个类自己的加载器

 /**
     * get class loader
     *
     * @param clazz
     * @return class loader
     */
    public static ClassLoader getClassLoader(Class clazz) {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable ex) {
            // Cannot access thread context ClassLoader - falling back to system class loader...
        }
        if (cl == null) {
            // No thread context class loader -> use class loader of this class.
            cl = clazz.getClassLoader();
            if (cl == null) {
                // getClassLoader() returning null indicates the bootstrap ClassLoader
                try {
                    cl = ClassLoader.getSystemClassLoader();
                } catch (Throwable ex) {
                    // Cannot access system ClassLoader - oh well, maybe the caller can live with null...
                }
            }
        }

        return cl;
    }

根据类加载机制,类按照顺序加载。加载后,类会被缓存在相应的加载器一段时间。当类加载器收到请求时,如果该类还在某一个类加载器缓存内,就是逐步向上委托查找缓存时找到的;如果已经不在缓存里了,就是从Bootstrap开始往下尝试加载时加载的

@SuppressWarnings("unchecked")
    private T createExtension(String name) {
        Class clazz = getExtensionClasses().get(name);
        if (clazz == null) {
            throw findException(name);
        }
        try {
            T instance = (T) EXTENSION_INSTANCES.get(clazz);
            if (instance == null) {
                EXTENSION_INSTANCES.putIfAbsent(clazz, clazz.newInstance());
                instance = (T) EXTENSION_INSTANCES.get(clazz);
            }
            injectExtension(instance);
            Set> wrapperClasses = cachedWrapperClasses;
            if (CollectionUtils.isNotEmpty(wrapperClasses)) {
                for (Class wrapperClass : wrapperClasses) {
                    instance = injectExtension((T) wrapperClass.getConstructor(type).newInstance(instance));
                }
            }
            return instance;
        } catch (Throwable t) {
            throw new IllegalStateException("Extension instance (name: " + name + ", class: " +
                    type + ") couldn't be instantiated: " + t.getMessage(), t);
        }
    }

所以我们应该判断传入的线程上下文是否为空,因为class.forname是用Class当前的类指定类加载器的,所以我们需要禁用到,使用传入的类加载器

ClassLoader classLoader = null == Thread.currentThread().getContextClassLoader() ? this.getClass().getClassLoader() : Thread.currentThread().getContextClassLoader();
                Class interfaceClass = Class.forName(interfaceName, false, classLoader);

你可能感兴趣的:(dubbo metadata层 深入类加载机制)