Debugging memory leaks with VisualVM

At work I had run into a memory leak when scrolling through large result sets returned from Hibernate. I thought I had fixed it by performing a evict()/clear()/flush() in the HibernateTemplate that I was using but suddenly the leak was back. I was using VisualVm to monitor the heap so I started poking around to see if there was anything to help diagnose where the leak was.

First thing I did was to take a heap dump.

I selected the classes and I see

Well THAT was not helpful. It turns out that the leak is in a class that only has one instance and it is holding onto thousands of objects.
Then on the summary page I notice the “Find 20 biggest objects by retained size:”.

I click it and a long time later I see

Shazam! There it is! In this faked up example I built there is a single Stack instance but it’s retained size is huge. That because VisualVM computed not just the size of that object but the sizes of all of the objects it was holding onto. How sweet is that. I found my memory leak in like 5 minutes.

Another useful tool!

One comment

  1. Hi Cory, Thanks for sharing this. I know about Heapdumps however, I am new to using Visual VM and also finding out memory leakage, thread related issues.
    So, could you please post a step by step guide on how you found it. For example, which tabs you clicked on VisualVM and its screenshots,

    Also, could you tell me some basic pointers about what/how to analysze heap dump and find out any memory leak or dead lock scenarios or thread race conditions.

    Thanks in advance!

Comments are closed.