12
I have child-first UrlClassLoader to load jar file dynamically. Then I do a reflection to invoke a method within loaded jar file. Once it is finished, I prefer to unload the classloader. Then I try to do some stress test code to make sure my code run smoothly. Basically, what I try to do is load and unload jar within looping statement. Here is my code:
for (int i = 0; i < 1000; i++) {
//Just to show the progress
System.out.println("LOAD NUMBER : " + i);
ChildFirstURLClassLoader classLoader = null;
try {
File file = new File("C:\\library.jar");
String classToLoad = "com.test.MyClass";
URL jarUrl = new URL("file:" + file.getAbsolutePath());
classLoader = new ChildFirstURLClassLoader(new URL[] {jarUrl}, null);
Class<?> loadedClass = classLoader.loadClass(classToLoad);
Method method = loadedClass.getDeclaredMethod("execute",
new Class[] {});
ClassLoader currCl= Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
method.invoke(null);
Thread.currentThread().setContextClassLoader(currCl);
method = null;
loadedClass = null;
} finally {
if (classLoader != null) {
classLoader.close();
classLoader = null;
}
}
}
When I'm running this code under JDK1.6, without classLoader.close(); statement, that code runs perfectly. But when I turn into JDK1.7, sometimes I get java.lang.OutOfMemoryError: PermGen space error. Unfortunately it occurs in inconsistent manner.