Friday, January 18, 2013

tools for Java memory usage analysis

1. jconsole

When you run a java program, you can use jconsole to monitor the program's general memory usage and the status of each thread of the program. Please note that this tool can not say how much memory is used by each object in your Java program. jconsole needs to show a graphic interface, so if you want to run it on Linux, please make sure you have xwindow support.
For instance, you can use the following command to start monitoring your running Java program with process id 15120:
jconsole 15120


2. jmap

This tool can be used to dump the heap of Java virtual machine when the machine is running a Java program. The dumped heap file can be analyzed by other tools, e.g., Eclipse memory analyzer .
For instance, you can use the following command to dump the heap of the running Java program with process ID 909, and the dumped file is named as heap-file.bin
jmap -dump:format=b,file=heap-file.bin 909

3. Eclipse memory analyzer

This tools is quite useful to look for memory leak or why a program takes so large memory, because it can find out the most memory-consuming objects in your Java program. This tool needs a heap dump to start its analysis. The heap dump can be obtained using jmap. Alternatively, when you run your Java program, you can also add -XX:+HeapDumpOnOutOfMemoryError as a parameter to the Java virtual machine. As a result, when the Java program runs out of memory, the Java virtual machine will automatically dump its heap in the current working directory (the dump file is named like java_pid15040.hprof).
Unfortunately, the Eclipse memory analyzer needs a lot of memory to analyze the heap dump file (e.g. usually it needs about 7GB memory to analyze a 2GB heap dump file). Thus, you usually need to change the heap size of your Eclipse (not the heap size of your Java program running in Eclipse) in your eclipse.ini file (which is usually located in the same folder as your eclipse binary executable file).