Java VisualVM is a tool that ships with Oracle JDK that makes profiling any Java application a piece of cake. In this post, I will show how to profile a server side application running on Tomcat. The approach will be same for any Java application (JBoss, WebSphere, command line, what have you).
Basic Usage
First, start the tool. From the <JDK>/bin folder, run:
./jvisualvm
Then, start the Java application. In my case, I started Tomcat. If you are in development, you can start the server from Eclipse. How you start the Java application has no impact on the tool.
The Applications pane will show all Java applications (JVM) running in the local machine. In our case, we see that tomcat is running.
Double click on the application to start working on that.
Click the monitor tab to get a high level overview of CPU and memory usage.
The CPU pane also shows GC performance. In the example above, only about 0.3% of the time is spent doing GC. Which is pretty good.
The Heap pane shows the current heap size and used space very nicely.
Heap Dump Analysis
A heap dump file has information about every Java object in memory and their relationships. Comparing two heap dump files taken before and after a stress test can show any object that may be leaking.
Before you run a stress test, first click Perform GC and then click Heap Dump. Run the stress test. Then do another GC and take a heap dump.
For a heap dump, click the Classes button and then Compare with another heap dump.
CPU and Memory Profiling
The tool offers two tabs for profiling – Sampler and Profiler. I am not sure what the difference is. For me, Sampler seems to work much better and faster.
Click either CPU or Memory button to start profiling. Run a stress test. Then click Stop to stop gathering data.
You can filter the list by entering a search string at the bottom.
Summary
Java VisualVM is one of the simplest to use profiling tool I have seen. I encourage you to try it out.