Joe Kearney
Joe Kearney

Reputation: 7537

Difference between System.gc() and dead object reclamation performed by taking a live-only heap dump?

There are at least two ways, directly or indirectly, of suggesting that the JVM expend effort collecting garbage:

In the latter, I can get hold a heap dump programmatically, for example through

hotspotMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
hotspotMBean.dumpHeap(filename, live);

What difference, if any, is there between what these two operations will do to collect non-strongly-reachable objects?

I believe I have evidence that the heap dump approach is more aggressive than System.gc() in the presence of some combination of weak references, RMI distributed garbage collection and invisible objects strongly-reachable from the stack. In particular that objects that are only weakly reachable locally and have become Unreferenced with respect to RMI appear to be collected only by the heap dump. I haven't yet been able to distil this into a small test case, but it is reproducible.

(Before I'm warned against relying on particular GC behaviour in prod code, I'm not. I discovered this while investigating a potential memory leak, and noticed that the result varied depending on when I took the heap dump. I'm just curious.)

This is using HotSpot 64-Bit Server VM 1.6.0_22 on Windows 7.

Upvotes: 3

Views: 609

Answers (1)

Guillaume
Guillaume

Reputation: 5553

The System.gc() is probably less aggressive because it just indicates the JVM that it should run the GC. The GC is then free to decide it should collect (find and free memory of) all dead objects, some of them, etc. It can decide the previous great collection happened too recently and it is not the time to collect all objects again.

I believe that dumping heap and explicitly asking only the living objects will cause the GC to compute precisely for each object if it should still be alive. This part of the collecting work being done, it does not cost much more to free the memory used by dead objects as well.

Alas I have no strong evidence of this behaviour and this is more a wild guess than a real explanation.

Upvotes: 1

Related Questions