Question

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 URLs 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, e.g. 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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top