Java VisualVM memory sampler - how to get the size of a specific class

aye picture aye · Jan 9, 2012 · Viewed 8k times · Source

My application uses a lot more memory than I think it suppose to use, and I'm trying to understand which class is using a large amount of the memory and maybe not releasing it.

I'm using VisualVM and in the memory sampler I can see that most of the memory is spent on Chars, Strings and Bytes, all my classes uses Strings, but as you know the VisualVM shows ALL Chars and Strings in the system (all the Chars are identical to the Strings which makes it hard to understand who holds them), as I understand the size of the other classes that hold these strings is calculated without the strings.

How can I see in this tool who are the "Real" largest classes - the ones that holds all these strings? (preferably if I can get from these classes to their Strings and not the other way around) I tried to use the "root to the nearest GC" in the heapDump but there are about 4,000,000 Strings so the chance of me finding the "problematic" ones is very small...

Thanks!!!

Answer

parasietje picture parasietje · Jan 9, 2012

If you do a heap dump, you can find the 20 largest objects (including all of the space it references). For anything more, I recommend using the OQL console which is very powerful.

Basically, you are searching for the following:

Lot of String's taking up 20Mb 
   --- kept alive by --->
HashSet#28839 
   --- kept alive by --->
MyOwnClass#88293

I propose you take a random string, find it's referrees and analyze this until you find out a possible suspect. Once you have this suspect, you can do an OQL query using http://visualvm.java.net/oqlhelp.html#rsizeof to find out the total size of these objects.