问题描述
我们正在创建多个子类加载器,以将多个子应用程序加载到 Java 应用程序容器"中,对热部署进行原型设计.当特定类加载器的类路径发生更改(即添加、删除、更新 jar)时,旧的类加载器将被丢弃(未引用),并为新的 jar 类路径创建一个新的类加载器.
We are creating multiple child classloaders to load in multiple subapplications into a Java application "container", prototyping hot deployment. When the classpath of a particular classloader has changed (i.e. jars have been added, deleted, updated), the old classloader is thrown away (unreferenced) and a new classloader is created for the new classpath of jars.
更新类路径后,触发热部署,我们进行了堆转储.堆转储(使用内存分析器)表明旧的类加载器没有被垃圾收集.父类加载器中的某些类正在缓存旧的类加载器.调用了以下内容来清除这些缓存:
After updating the classpath, triggering the hot deployment, we took a heap dump. The heap dump (using Memory Analyzer) indicates that the old classloaders were not being garbage collected. Certain classes in the parent classloader were caching the old classloaders. The following things were invoked to clear these caches:
java.lang.ResourceBundle.clearCache(classLoader);
org.apache.commons.logging.LogFactory.release(classLoader);
java.beans.Introspector.flushCaches();
即使在清除了上述缓存之后,旧的类加载器仍然没有被垃圾回收.对类加载器的其余引用包括以下内容:
Even after clearing the above caches, the old classloader were still not being garbage collected. The remaining references to the classloader included the following:
- 类加载器加载的类
- java.lang.Package 由类加载器自己创建
- 类加载器自己创建的java.lang.ProtectionDomain
以上都是类加载器中的循环引用,应该会触发垃圾回收.我不确定为什么不是.有谁知道为什么即使使用循环引用,旧的类加载器仍然没有被垃圾收集?
All the above are circular references within the classloader, which should trigger a garbage collection. I'm not sure why it is not. Does anybody know why the old classloaders are still not being garbage collected even with the circular references?
推荐答案
一直听说Classloader
卸载有问题.当没有对对象实例的引用并且不需要卸载类时,它们理论上会被垃圾收集,但在实践中,它似乎更有问题.微妙的引用可能会泄漏并阻止 Classloader
被回收.在应用服务器中,经过多次重新部署循环,我有时会遇到 OutOfMemoryError: PermGen space
.
I always heard that Classloader
unloading was problematic. They are theoretically garbage collected when there is not reference to the object instances and class unloading is not necessary, but in practice it seems like to be more problematic. Subtle references may leak and prevent the Classloader
from being reclaimed. In application servers, after numerous redeploy cycle, I sometimes got a OutOfMemoryError: PermGen space
.
所有这一切都是说我猜某处有一个讨厌的引用阻止它被收集——也许内存分析器没有正确地跟踪链接.正如这些文章中所述,这一切似乎都可能发生:
All that to say that I guess there is a nasty reference somewhere that prevent it from being collected -- maybe the memory analyzer didn't followed the link correctly. It seems like all this can happen, as described in these articles:
- 类加载器泄漏:可怕的 PermGen 空间异常
- 如何修复可怕的 PermGen空间异常
另外,我不知道你在做什么,但如果你可以等待 JDK 7,你可以看看 AnonymousClassLoader
.将引入它们以更好地支持动态语言,如本文所述:
Also, I don't know exactly what you are doing, but if you can wait for JDK 7, you could have a look at AnonymousClassLoader
. They will be introduced to better support dynamic language, as explained in this post:
- 第一次体验 InvokeDynamic
希望对你有帮助.
这篇关于何时以及如何将 java 类加载器标记为垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!