Picking Java's brains

Ever wondered what Java does with all that memory? Not so long ago you'd have to trigger a heap dump and then grovel over it with arcane tools.

But since the release of Java 1.5 (old news, I know, but still new to me) two wonderful utilities are included in the JDK:
  • jstat, which outputs statistics in a vmstat-like format (if you're familiar with Unix administration)
  • jmap, whose output is a bit friendlier.
jstat is very useful when you want to take several samples over a period of time to watch trends, but most people will want jmap, especially with the -heap option; this tells you the current (and maximum) sizes of various parts of the Java memory, along with how much of that memory is actually used.

jmap also supports other run modes; the most useful (at least to me) are:

-histo gives you a listing of the objects in the Java heap, listed by class. For each class, it tells you how many objects of that class are in the heap and how much memory they use. The listing is (at least on my system) in decreasing memory size order.

-permstat gives you a listing of the objects in the permanent generation; interesting (although unfortunately not really detailed enough) when something[tm] is eating your permgen space...

jmap can also be used to generate a heap dump, if you're so inclined. This can then be further inspected with jhat or similar tools.

And the best part? Well, there are two:
  1. These tools use the built-in instrumentation of the JVM, so you don't need to pass any funky commandline options (if you're running them on a local JVM, that is)
  2. They work on running processes!

No comments: