我有子优先的UrlClassLoader来动态加载jar文件。然后,我执行一个反射来调用加载的jar文件中的一个方法。一旦完成,我更喜欢卸载类加载器。然后,我尝试执行一些压力测试代码,以确保我的代码能够顺利运行。基本上,我尝试做的是在循环语句中加载和卸载jar。下面是我的代码:
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;
}
}
}当我在JDK1.6下运行这段代码时,没有使用classLoader.close();语句,这段代码运行得很好。但当我转向JDK1.7时,有时会收到java.lang.OutOfMemoryError: PermGen space错误。不幸的是,它以不一致的方式发生。
发布于 2012-12-21 17:11:59
确认泄漏来源的最简单方法是使用探查器监视内存使用情况。试试JProfiler或VisualVM。它将使您能够精确定位泄漏的确切位置,并为您提供是否以及如何修复它的线索。
https://stackoverflow.com/questions/13953714
复制相似问题