Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to FORCE weak and/or soft referenced objects to be GC'd in Java?

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?

like image 710
Scott Avatar asked Aug 06 '11 16:08

Scott


1 Answers

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.

like image 188
Paul Bellora Avatar answered Oct 14 '22 15:10

Paul Bellora