Java for sys admins: How do I tell how much heap space java is using?

Created: 09 Oct 2006

I haven’t actually managed to complete a single article about java application administration, having completely overestimated my free time. I happened to talk to Adrian about a problem he’d had with tomcat using up the allocated space for the permanent generation. He was wondering how to monitor the memory usage of a JVM, from within a script, without writing custom code.

If you are using a version of the JRE from 1.5 onwards, it is simple; use jstat. Firstly, identify the vmid of the JVM you wish to monitor. On Solaris and Linux, the two operating systems I use, the vmid is the process ID of the jvm process. In their documentation, Sun suggest that the definitive method of identifying the processes is by running jps, another utility supplied with the JRE from 1.5 onwards.

 jstat -gc <pid>

will display gargage collection statistics. You will need to run jstat as the user that the jvm is running as, or be root. The permanent generation capacity is displayed in the column headed PC and the permanent generation usage in the column headed PU (see the jps manpage for more information on the output format).

 # /opt/jdk-1.5/bin/jstat -gc 9860
 S0C    S1C    S0U    S1U      EC       EU        OC         OU       PC     PU    YGC     YGCT    FGC    FGCT     GCT   
128.0  128.0   0.0    0.0   43776.0   111.9    466048.0   12621.6   24192.0 23942.1   6065    9.950 6060   987.881  997.831

Jstat can also be run in a continuous monitoring mode, similar to that of the unix commands vmstat and iostat, which prints a line of output at regular intervals. It differs from vmstat in that the default interval specification is in milliseconds, although you can specify seconds by the addition of an “s” to the number. This will show gc and memory stats once per second:

 jstat -gc <pid> 1s

Many important jvm metrics can be obtained from jstat - check the manpage - and it’s a very useful tool. In my opinion it’s worth upgrading to 1.5 for this and other extra monitoring features.