Loading order of Tomcat classloader

Recently, the project encountered an unstable class loading order in Tomcat 7.0.26. I pulled the source code on github and looked at it and figured it out. The problem in the project is that we can define the loading order of jar files under webapp\WEB-INF\lib by alphabetical order, but it does not work under tomcat\lib\ext. In fact, the problem is that the jar and tomcat in these two locations are loaded with different classloaders, so the results are naturally different.

 

For common and system classes , tomcat uses the classloader generated by org.apache.catalina.startup.ClassLoaderFactory, and the entry is Bootstrap.initClassLoaders(). This classloader uses java api: File.list() to traverse the jar files in the folder. See the javadoc for an explanation of the order.

 

     * <p> There is no guarantee that the name strings in the resulting array
     * will appear in any specific order; they are not, in particular,
     * guaranteed to appear in alphabetical order.

 

 

In WebappClassloader, tomcat sorts the list obtained by File.list() again in alphabetical order.

org.apache.naming.resources.FileDirContext

 

    protected List<NamingEntry> list(File file) {

        List<NamingEntry> entries = new ArrayList<NamingEntry>();
        if (!file.isDirectory())
            return entries;
        String[] names = file.list();
        if (names==null) {
            /* Some IO error occurred such as bad file permissions.
               Prevent a NPE with Arrays.sort(names) */
            log.warn(sm.getString("fileResources.listingNull",
                                  file.getAbsolutePath()));
            return entries;
        }

        Arrays.sort(names);             // Sort alphabetically
        NamingEntry entry = null;
        ......

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326481366&siteId=291194637