It is not uncommon that you need to watch the runtime performance of a Java application on a server. In this post, I'll show you how to set up a target JVM so you can monitor its cpu, heap memory, threads usage from a specific JMX client - VisualVM. VisualVM is similar to JConsole, a JMX-compliant monitoring tool, but is more advanced.

To use a JMX client, the setup you need to do first are:

On the Target server where JVM runs, you need to enable JMX Agent for the JVM.

On the local machine where you want to monitor your Java application from, you need a JMX client. For this post, I chose VisualVM.

To prevent other JMX client from accessing your JMX Agent, you want to turn on authentication when your JMX client connects to your JMX Agent.

Enable JMX Agent for JVM

Your java runtime is not enabled with JMX by default unless you explicitly specify to turn it on. With JMX agent enabled, you can use a JMX Client to tap into your JVM to monitor its memory usage and performance at runtime. To enable JMX for a JVM, please refer to Enable JMX Agent for JVM.

Install VisualVM

VirtualVM is like JConsole, but it has more advanced monitoring features for developers:

allowing the user to analyze thread execution

the ability to profile/sample CPU and memory usage

To install it on your local development machine, you can download it here. If you're like me as a Mac user, follow these steps:

If your target server where JMX Agent does not require username/password, just leave those blank when connecting.

VisualVM Quick Guide

To see what you usually see (cpu, classes, memory, etc.) as if you were using JConsole, double click on display name (e.g. controlRole or monitorRole) on the left panel as seen below:

To generate Heap Dump on the Target JVM server,

Select Monitor tabClick Heap Dump

To analyze threads and profile CPU & memory:

Access JMX Agent as controlRole also allows you analyze threads and profile CPU & memory. To learn more about profiling/sampling using VisualVM, please see this article.

To analyze garbage collection (GC)

If you just want to visually get an idea about how often the major GC or minor GC took place, use JConsole which should be available under $JAVA_HOME/bin directory. On your mac, you can simply launch JConsole:

jconsole&

The following JConsole screen shows the app has been using up memory that major GC keeps happening.

Similarly, you can use Visual GC plug-in for VisualVM. It requires jstatd on the server side. First install Visual GC plugin: