有没有办法在 Java 中强制对弱引用和/或软引用对象进行 GC?
这是我的用例。我们正在尝试缩小应用程序中潜在内存泄漏的范围,并且我们正在使用内存分析工具对堆进行快照,以便我们可以查找对象实例和引用。 (如果有帮助,我们正在使用 YourKit。)
该应用程序广泛使用动态和 CGLIB 代理,最终在 WeakHashMap 中存储大量对类和类加载器的引用。
在我们的测试用例运行之后,我们期望对对象 X 及其类加载器的所有硬引用都消失,但由于测试用例最终涉及许多代理,因此我们留下了许多弱/软引用。 (我只能找到 WeakHashMap 引用,但 YourKit 将弱引用和软引用包装到摘要中的一个行项目中,因此我无法确定我没有在某处丢失软引用。)
即使在请求完整 GC 之后也是如此来自 JVM。 (在服务器模式下使用 sun 1.6.0_23 JDK。)
似乎 JVM 承认只有对这些对象的弱/软引用,但我无法强制它 GC 这些东西100%确定。 (所以,我想要的是让它从堆中完全消失,并且它的类加载器对 permgen 的使用也消失。)
有人知道配置和/或强制 JVM 处理仅软/弱引用的对象的方法吗?
Here's my use case. We are trying to narrow down a potential memory leak in an application, and we are using a memory analysis tool to snapshot the heap so we can look for object instances and references. (In case it helps, we're using YourKit.)
This application makes extensive use of dynamic and CGLIB proxies, which end up storing tons of references to classes and classloaders in WeakHashMaps.
After our test case runs, we are expecting all hard references to object X and its classloader to be gone, but since there were many proxies involved in the test case in the end we have many weak/soft references left to it. (I can only find WeakHashMap references, but YourKit wraps both weak and soft references into one line item in the summary so I can't be sure I'm not missing a soft reference somewhere.)
This is true even after requesting a full GC from the JVM. (Using the sun 1.6.0_23 JDK in server mode.)
It seems as though the JVM admits there are only weak/soft references to these objects, but I can't get force it to GC these things to be 100% sure. (So, what I want is for this to disappear entirely from the heap and its classloader usage of permgen to also go away.)
Anyone know of a way to configure and/or force the JVM to dispose of objects only soft/weakly referenced?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用 GC 应该始终释放所有弱可达对象(假设通过调用 System.gc 发出的“请求”实际上已被授予)。如果 GC 没有清除弱引用,则意味着对象至少是软可达的。
清除软引用比较棘手,因为这取决于 JVM 的判断力。保证清除软可达对象的唯一方法是引发
OutOfMemoryError
。这个技巧在此讨论中进行了演示。Calling GC should always release all weakly-reachable objects (assuming the "request" made by calling
System.gc
is actually granted). If weak references are not getting cleared by GC, it means the objects are at least softly reachable.Clearing soft references is trickier, as this is up to the JVM's discretion. The only way to guarantee clearing of softly-reachable objects is to cause an
OutOfMemoryError
to be thrown. This trick is demonstrated in this discussion.