gpt4 book ai didi

java - JDK1.7 类加载器内存泄漏

转载 作者:搜寻专家 更新时间:2023-10-30 21:12:42 29 4
gpt4 key购买 nike

我有 child 优先的 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 错误。不幸的是,它以不一致的方式发生。

最佳答案

确认泄漏来源的最简单方法是使用分析器监视内存使用情况。试试 JProfiler 或 VisualVM。它将使您能够查明泄漏的确切位置,并为您提供是否可以修复以及如何修复的线索。

关于java - JDK1.7 类加载器内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13953714/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com