[tomcat7源碼學習]ClassLoader加載Tomcat的依賴

ClassLoader加載Tomcat的依賴

經過查看catalina.bat中設置的classpath只有bootstrap.jartomcat-juli.jar,這兩個都只包含Bootstrap執行時所須要的類,因此若是要進行後續操做,都須要再加載。經過前面返回的ClassLoader加載apache

1.在BootStrap中加載完成ClassLoader以後就回到了init方法中.bootstrap

Thread.currentThread().setContextClassLoader(catalinaLoader);

    SecurityClassLoad.securityClassLoad(catalinaLoader);

這裏就開始加載tomcat所須要的classtomcat

2.進入SecurityClassLoad.securityClassLoad測試

public static void securityClassLoad(ClassLoader loader)
        throws Exception {

    if( System.getSecurityManager() == null ){
        return;
    }

    loadCorePackage(loader);
    loadCoyotePackage(loader);
    loadLoaderPackage(loader);
    loadRealmPackage(loader);
    loadSessionPackage(loader);
    loadUtilPackage(loader);
    loadValvesPackage(loader);
    loadJavaxPackage(loader);
    loadConnectorPackage(loader);
    loadTomcatPackage(loader);
}

就能夠大概看出加載class的順序了,各個方法裏面都是加載指定的Class,也就是要加載那些類都寫死了,若是咱們要作什麼擴展,只是把寫好的類扔到包中,應該就會出問題。。優化

###總結###this

1.對於tomcat本身要使用的類都是指定類名進行加載的spa

2.在查看啓動時classpath的設置過程當中,反編譯了一下生成的BootStrap.class,和源碼相比發現其中少import了一個的類:org.apache.catalina.Globals,開始還覺得是在編譯過程當中作了什麼處理,最後查看這個類是final的,再到網上一查,原來在編譯時會對final作優化,會把final變量名直接替換成其相應的值,而後本身也作了一個小測試,確實如此。。。。看來之前疏忽了。。。code

3.在回頭查看ClassLoader的過程當中,發現每一個Class都會先判斷,也就是已經加載了的,就不會再加載rem

Class c = findLoadedClass(name);
        if (c == null) {
            long t0 = System.nanoTime();
            try {
                if (parent != null) {
                    c = parent.loadClass(name, false);
                } else {
                    c = findBootstrapClassOrNull(name);
                }
            } catch (ClassNotFoundException e) {
                // ClassNotFoundException thrown if class not found
                // from the non-null parent class loader
            }

            if (c == null) {
                // If still not found, then invoke findClass in order
                // to find the class.
                long t1 = System.nanoTime();
                c = findClass(name);

                // this is the defining class loader; record the stats
                sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                sun.misc.PerfCounter.getFindClasses().increment();
            }
        }
        if (resolve) {
            resolveClass(c);
        }

先調用了findLoadedClass,若是沒有,才繼續查找get

相關文章
相關標籤/搜索