简体   繁体   中英

URLClassLoader slow under Tomcat

I have a classpath directory containing about 30 jars. In my plain console application I am creating an URLClassLoader where I initialize it with the list of URL s pointing to all these jars.

URL[] urls = new URL[] {
    new URL("jar:file:/D:/Work/temp/jars/antlr-2.7.7.jar!/"),
    new URL("jar:file:/D:/Work/temp/jars/aopalliance-1.0.jar!/"),
    new URL("jar:file:/D:/Work/temp/jars/c3p0-0.9.1.jar!/"),
    ...
}
URLClassLoader cl = new URLClassLoader(urls, getClass().getClassLoader());
Class<?> c = cl.loadClass(...);
etc...

Like this everything is working fine, taking a few milliseconds to load a single class from my URLClassLoader .

Now I take this snippet of code and make it run under Tomcat, eg triggered at a simple web request inside a servlet's doGet() . Surprisingly, the time lapse taken to load an average class becomes 10-15 times longer, making the whole initialization time inacceptable. The issue holds for at least Tomcat versions both 6 and 7.

Any ideas?

Try new URLClassLoader(urls); . Does this improve the performance?

Common and WebappX class loaders may affect the performance of loading a class. Please see following link for more details of Tomcat's Class Loader.

http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html

It's absolutely silly, but the issue has gone away after I rebooted my machine :) I am running Windows 7, Oracle JDK 1.6/1.7, Tomcat 6/7, the problem persisted for any combination of these. The profiler was showing me that it was sun.net.www.protocol.jar.URLJarFile 's <init> which was slowing down the whole stuff. Probably something went wrong with jars cache so that unnecessary initialization executed for every class requested from a jar.

Update: I've found how to fix the issue with class loading being so slow and getting even slower as long as you are not rebooting your machine. Instead of using

new URL("jar:file:/D:/Work/temp/jars/antlr-2.7.7.jar!/")

I've tried

new URL("file:/D:/Work/temp/jars/antlr-2.7.7.jar")

The URLClassloader handles properly this kind of URLs as jars even without "jar" protocol being specified. However it drastically increased the performance! Still I don't know the exact reason for this behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM