有没有办法在Java中强制弱引用对象和/或软引用对象进行GC? [英] Is there a way to FORCE weak and/or soft referenced objects to be GC'd in Java?

查看:304
本文介绍了有没有办法在Java中强制弱引用对象和/或软引用对象进行GC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的用例。我们试图缩小应用程序中潜在的内存泄漏,并且我们使用内存分析工具对堆进行快照,以便查找对象实例和引用。 (如果有帮助,我们使用YourKit。)



这个应用程序大量使用动态代码和CGLIB代理,这些代理最终存储了对类和类加载器的大量引用在WeakHashMaps中。



在我们的测试用例运行后,我们预计所有对对象X及其类加载器的硬引用都会消失,但由于测试中涉及很多代理最后,我们还有很多弱/弱的参考。 (我只能找到WeakHashMap引用,但YourKit将弱引用和软引用包含在摘要中的一个行项目中,所以我不能确定我不会在某处丢失软引用。)



即使在从JVM请求完整GC之后也是如此。 (在服务器模式下使用sun 1.6.0_23 JDK。)



它似乎好像JVM承认只有弱/这些对象,但我不能强迫它把GC这些东西100%确定。 (所以,我想要的是,它完全从堆中消失,并且它的类加载器使用permgen也会消失。)



任何人都知道配置和/或强制JVM仅处理软/弱引用的对象?调用GC应始终释放所有弱可访问的对象(假设通过调用 System.gc 进行的请求实际上被授予)。如果弱引用没有被GC清除,这意味着对象至少可以轻松访问。



清除软引用更加棘手,因为这取决于JVM的判断。保证清除可轻松访问的对象的唯一方法是引发 OutOfMemoryError 。这个技巧在这个讨论中得到了展示。


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?

解决方案

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.

这篇关于有没有办法在Java中强制弱引用对象和/或软引用对象进行GC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆