Java JVM Monitoring
Java JVM monitoring means watching a running Java process from the inside: how full the heap is, how often the garbage collector runs, how many threads exist and what they are doing, and which methods use the CPU. The JDK ships every tool you need for this, so you can inspect a production server without installing anything or restarting the application.
This lesson covers the command-line tools jps, jcmd and jstat, thread dumps, native memory tracking, Java Flight Recorder (JFR) and the java.lang.management API. It ends by adding a /metrics endpoint to a server and using it to catch a memory leak. Examples were run on JDK 21 on Linux, with the JVM options from Java JVM Options.
Java JVM Monitoring Tools at a Glance
| Tool | What it shows | Typical command |
|---|---|---|
jps | Running Java processes and their IDs | jps -l |
jcmd | Almost everything: flags, heap, threads, GC, JFR | jcmd <pid> help |
jstat | Live GC and memory statistics, every N ms | jstat -gcutil <pid> 1000 |
jstack | Thread dump (same as jcmd <pid> Thread.print) | jstack <pid> |
jfr | Reads Java Flight Recorder files | jfr summary app.jfr |
| JMX / MXBeans | The same data from inside your Java code | ManagementFactory.getMemoryMXBean() |
| JDK Mission Control / VisualVM | Graphical views of JFR files and live JVMs | Desktop apps |
Note: Run these tools as the same user as the Java process. For a service running as
courseapp, usesudo -u courseapp jcmd <pid> ..., or the tool reports that it cannot attach.
Find Running JVMs With jps
All examples in this lesson watch the program below. Three worker threads build receipt strings in a loop, which creates steady CPU load and garbage.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class OrderWorker {
static final List<String> recentOrders = new ArrayList<>();
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int w = 0; w < 3; w++) {
pool.submit(() -> {
while (true) {
process();
}
});
}
System.out.println("OrderWorker running, pid " + ProcessHandle.current().pid());
Thread.sleep(Long.MAX_VALUE);
}
static void process() {
StringBuilder receipt = new StringBuilder();
for (int i = 0; i < 200; i++) receipt.append("line-").append(i);
synchronized (recentOrders) {
recentOrders.add(receipt.toString());
if (recentOrders.size() > 5_000) recentOrders.clear();
}
}
}
javac OrderWorker.java
java -Xmx256m -XX:NativeMemoryTracking=summary OrderWorker &
jps -l
OrderWorker running, pid 778
778 OrderWorker
1204 jdk.jcmd/sun.tools.jps.Jps
How it works:
jpslists every JVM owned by the current user.-lshows the full main class or JAR path, which helps when several apps run on one server.ProcessHandle.current().pid()prints the process ID from inside Java. Logging it at startup saves a lookup later.-XX:NativeMemoryTracking=summaryis enabled now because it can only be switched on at startup. It is used later in this lesson.
Inspect a Live JVM With jcmd
jcmd sends a command to a running JVM and prints the answer. jcmd <pid> help lists every available command.
jcmd 778 VM.version
jcmd 778 VM.uptime
778:
OpenJDK 64-Bit Server VM version 21.0.12.1+1-1-24.04.4-Ubuntu
JDK 21.0.12.1
778:
7.106 s
Check the Effective JVM Flags
jcmd 778 VM.flags
778:
-XX:CICompilerCount=2 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=2 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=98566144 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=268435456 -XX:MaxNewSize=160432128 -XX:MinHeapDeltaBytes=1048576 -XX:MinHeapSize=8388608 -XX:NativeMemoryTracking=summary -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:SoftMaxHeapSize=268435456 -XX:+UseCompressedOops -XX:+UseG1GC
Check Heap Usage
jcmd 778 GC.heap_info
778:
garbage-first heap total 227328K, used 16082K [0x00000000f0000000, 0x0000000100000000)
region size 1024K, 9 young (9216K), 7 survivors (7168K)
Metaspace used 407K, committed 576K, reserved 1114112K
class space used 31K, committed 128K, reserved 1048576K
How it works:
VM.flagsshows the final flags of the running process, including values the JVM chose itself.MaxHeapSize=268435456is the 256 MB from-Xmx256m. This answers "which options is production really using?" without access to the start script.GC.heap_infoshows the G1 heap: 227 MB reserved, about 16 MB used, divided into 1 MB regions. Metaspace (class metadata) is reported separately because it lives outside the heap.- Every
jcmdanswer starts with the process ID, so output from several JVMs is easy to tell apart.
Useful jcmd command | Purpose |
|---|---|
VM.system_properties | All -D and JDK properties |
VM.command_line | The full command used to start the JVM |
GC.class_histogram | Object count and bytes per class (a quick leak check) |
GC.heap_dump /tmp/app.hprof | Write a heap dump without crashing |
Thread.print | Thread dump |
VM.native_memory summary | Memory inside and outside the heap |
JFR.start / JFR.dump / JFR.stop | Control Java Flight Recorder |
Watch Garbage Collection Live With jstat
jstat samples GC statistics at a fixed interval. -gcutil shows how full each memory area is as a percentage.
# every 1000 ms, 3 samples
jstat -gcutil 778 1000 3
S0 S1 E O M CCS YGC YGCT FGC FGCT CGC CGCT GCT
- 89.65 23.74 7.95 70.79 24.35 152 0.392 0 0.000 0 0.000 0.392
- 100.00 19.01 7.95 70.79 24.35 183 0.451 0 0.000 0 0.000 0.451
- 92.62 63.31 7.95 70.79 24.35 215 0.505 0 0.000 0 0.000 0.505
| Column | Meaning |
|---|---|
S0, S1 | Survivor spaces (% used); G1 uses only one at a time, so the other shows - |
E | Eden, where new objects are created (% used) |
O | Old generation, where long-lived objects end up (% used) |
M, CCS | Metaspace and compressed class space (% used) |
YGC / YGCT | Young collections: count and total seconds |
FGC / FGCT | Full collections: count and total seconds |
CGC / CGCT | Concurrent cycles: count and total seconds |
GCT | Total GC time in seconds |
How it works:
- About 30 young collections happen per second (
YGCgoes 152 → 183 → 215), but they take only about 2 ms each (YGCTrises by ~0.06 s per second). That is healthy: the workers create short-lived garbage that dies young. Ostays at 7.95%. If the old generation kept growing between samples and never dropped, objects would be surviving that should not, which is the classic sign of a memory leak.FGCstays at 0. Full collections stop the whole application, so a risingFGCin production deserves attention.
Take a Java Thread Dump
A thread dump lists every thread with its state and current stack. It answers "what is the app doing right now?" and is the first thing to collect when an application hangs or uses 100% CPU.
jcmd 778 Thread.print
"pool-1-thread-1" #18 [797] prio=5 os_prio=0 cpu=6623.84ms elapsed=11.62s tid=0x00007f49e4633400 nid=797 runnable [0x00007f49cc1fd000]
java.lang.Thread.State: RUNNABLE
at OrderWorker.lambda$main$0(OrderWorker.java:14)
at OrderWorker$$Lambda/0x00007f4970000a08.call(Unknown Source)
at java.util.concurrent.FutureTask.run(java.base@21.0.12.1/FutureTask.java:317)
at java.util.concurrent.ThreadPoolExecutor.runWorker(java.base@21.0.12.1/ThreadPoolExecutor.java:1144)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(java.base@21.0.12.1/ThreadPoolExecutor.java:642)
...
| Part | Meaning |
|---|---|
"pool-1-thread-1" | Thread name; name your own threads so dumps are readable |
cpu=6623.84ms elapsed=11.62s | CPU time used vs. wall-clock age; this thread is busy 57% of the time |
nid=797 | Native (Linux) thread ID, matches top -H -p <pid> |
RUNNABLE | State: also BLOCKED, WAITING, TIMED_WAITING |
at OrderWorker...(OrderWorker.java:14) | The exact line the thread is executing |
How it works:
- The worker threads are
RUNNABLEinside thewhile (true)loop at line 14, which matches the program. A thread stuck inBLOCKEDwith the textwaiting to lockpoints to lock contention. - If the JVM finds a deadlock, the dump ends with a section titled
Found one Java-level deadlock:that names the threads and locks involved. - Take three dumps a few seconds apart. A thread that shows the same stack every time is truly stuck; one that changes is just busy.
Note:
top -H -p <pid>shows CPU per thread with its Linux ID. Convert the busiest ID to hex (printf '%x\n' 797) and search the dump fornid=0x31don older JDKs, ornid=797on JDK 21, to find the Java stack burning the CPU.
Track Memory Outside the Heap With Native Memory Tracking
A JVM with -Xmx256m often uses more than 256 MB of RAM. Native Memory Tracking (NMT) shows where the rest goes. It must be enabled at startup with -XX:NativeMemoryTracking=summary.
jcmd 778 VM.native_memory summary
778:
Native Memory Tracking:
(Omitting categories weighting less than 1KB)
Total: reserved=1708981KB, committed=306437KB
malloc: 8157KB #9650
mmap: reserved=1700824KB, committed=298280KB
- Java Heap (reserved=262144KB, committed=238592KB)
(mmap: reserved=262144KB, committed=238592KB, at peak)
- Class (reserved=1048686KB, committed=238KB)
(classes #719)
...
How it works:
- Committed memory is actually backed by RAM; reserved is only address space. Compare the committed total (about 300 MB here) with the process's real memory (
RESintop). - The Java heap is 233 MB committed. The remaining categories (
Class,Thread,Code,GC,Internal) explain the difference, which is why a container needs a memory limit above-Xmx. - NMT costs a few percent of performance, so enable it while investigating and leave it off otherwise.
Record Production Data With Java Flight Recorder
Java Flight Recorder (JFR) is a low-overhead event recorder built into the JVM. It records CPU samples, allocations, GC pauses, lock contention, I/O and more, with an overhead of about 1% using the default settings, so it is safe to run on production servers.
# record for 10 seconds into a file
jcmd 778 JFR.start name=orders duration=10s filename=orders.jfr
778:
Started recording 1. The result will be written to:
/home/deploy/orders.jfr
Read the file with the jfr tool:
jfr summary orders.jfr
Version: 2.1
Chunks: 1
Start: 2026-11-18 04:48:44 (UTC)
Duration: 10 s
Event Type Count Size (bytes)
=============================================================
jdk.GCPhaseParallel 60242 1729049
jdk.TenuringDistribution 4770 57585
jdk.ObjectAllocationSample 1484 23206
jdk.MetaspaceChunkFreeListSummary 1272 25244
...
JDK 21's jfr view command builds ready-made reports:
jfr view hot-methods orders.jfr
jfr view gc-pauses orders.jfr
Java Methods that Executes the Most
Method Samples Percent
--------------------------------------------------------------- ------- -------
java.lang.AbstractStringBuilder.ensureCapacityInternal(int) 395 70.54%
java.util.Arrays.copyOf(byte[], int) 112 20.00%
java.util.ArrayList.add(Object, Object[], int) 50 8.93%
jdk.internal.util.ArraysSupport.newLength(int, int, int) 3 0.54%
GC Pauses
---------
Total Pause Time: 589 ms
Number of Pauses: 318
Minimum Pause Time: 0.540 ms
Median Pause Time: 1.80 ms
Average Pause Time: 1.85 ms
How it works:
hot-methodsshows that 90% of CPU samples are spent growing theStringBuilder(ensureCapacityInternalandArrays.copyOf). The fix is clear without guessing: create it with enough capacity,new StringBuilder(2_000).gc-pausesconfirms the GC is not a problem: 318 pauses averaging 1.85 ms.- To record from startup instead, add
-XX:StartFlightRecording=duration=60s,filename=startup.jfrto the JVM options. Open.jfrfiles in JDK Mission Control for graphs and flame charts.
jfr view report | Shows |
|---|---|
hot-methods | Methods using the most CPU |
allocation-by-class | Classes allocating the most memory |
gc-pauses | Pause statistics |
contention-by-site | Where threads wait for locks |
exception-count | Exceptions thrown, by type |
Monitor the JVM From Java Code With MXBeans
The java.lang.management package exposes the same data as jcmd through MXBeans. Your application can read its own health and log it, alert on it or publish it.
| MXBean | Obtained with | Key methods |
|---|---|---|
MemoryMXBean | ManagementFactory.getMemoryMXBean() | getHeapMemoryUsage(), getNonHeapMemoryUsage() |
GarbageCollectorMXBean | ManagementFactory.getGarbageCollectorMXBeans() | getCollectionCount(), getCollectionTime() |
ThreadMXBean | ManagementFactory.getThreadMXBean() | getThreadCount(), findDeadlockedThreads() |
RuntimeMXBean | ManagementFactory.getRuntimeMXBean() | getUptime(), getInputArguments() |
OperatingSystemMXBean | ManagementFactory.getOperatingSystemMXBean() | getSystemLoadAverage(), getAvailableProcessors() |
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
public class JvmStats {
static final long MB = 1024 * 1024;
public static void main(String[] args) throws InterruptedException {
List<int[]> data = new ArrayList<>();
for (int round = 1; round <= 3; round++) {
for (int i = 0; i < 2_000; i++) data.add(new int[2_500]); // ~20 MB per round
printStats(round);
Thread.sleep(500);
}
}
static void printStats(int round) {
MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
MemoryUsage heap = memory.getHeapMemoryUsage();
MemoryUsage nonHeap = memory.getNonHeapMemoryUsage();
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
long gcCount = 0, gcMillis = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
gcCount += Math.max(gc.getCollectionCount(), 0);
gcMillis += Math.max(gc.getCollectionTime(), 0);
}
System.out.printf("Round %d: heap %d/%d MB, non-heap %d MB, threads %d, GCs %d (%d ms), load %.2f%n",
round, heap.getUsed() / MB, heap.getMax() / MB, nonHeap.getUsed() / MB,
threads.getThreadCount(), gcCount, gcMillis, os.getSystemLoadAverage());
}
}
java -Xmx256m JvmStats
Round 1: heap 19/256 MB, non-heap 1 MB, threads 6, GCs 3 (7 ms), load 1.65
Round 2: heap 39/256 MB, non-heap 3 MB, threads 6, GCs 5 (19 ms), load 1.65
Round 3: heap 57/256 MB, non-heap 3 MB, threads 6, GCs 6 (26 ms), load 1.52
How it works:
- The program keeps every array in
data, so used heap grows by about 20 MB per round, exactly what a leak looks like from the inside. - G1 reports several collector beans (young, concurrent, old). The loop adds them up.
Math.max(..., 0)guards against-1, which a bean returns when a value is not available. getThreadCount()is 6 even though the program starts no threads: the JVM always runs helpers such asReference Handler,FinalizerandSignal Dispatcher.
Real-World Example: A /metrics Endpoint That Catches a Memory Leak
This server publishes JVM health as JSON at /metrics. Its /api/report endpoint has a bug: it caches 8 MB per request and never removes anything. A small watch script polls /metrics, notices the heap climbing past 80% and collects a class histogram automatically.
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public class MetricsServer {
private static final AtomicLong REQUESTS = new AtomicLong();
private static final double HEAP_WARN = 0.80; // warn above 80% heap
private static final long MB = 1024 * 1024;
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 8080), 0);
server.setExecutor(Executors.newFixedThreadPool(4));
List<byte[]> reportCache = new ArrayList<>();
server.createContext("/api/report", exchange -> {
REQUESTS.incrementAndGet();
reportCache.add(new byte[8 * 1024 * 1024]); // bug: cache never shrinks
send(exchange, 200, "{\"students\":312}");
});
server.createContext("/metrics", exchange -> send(exchange, 200, metricsJson()));
server.start();
System.out.println("MetricsServer on http://127.0.0.1:8080");
}
static String metricsJson() {
MemoryUsage heap = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
long gcCount = 0, gcMillis = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
gcCount += Math.max(gc.getCollectionCount(), 0);
gcMillis += Math.max(gc.getCollectionTime(), 0);
}
double heapRatio = (double) heap.getUsed() / heap.getMax();
String status = heapRatio > HEAP_WARN ? "WARN" : "OK";
long uptimeSec = ManagementFactory.getRuntimeMXBean().getUptime() / 1000;
return String.format(
"{\"status\":\"%s\",\"uptimeSec\":%d,\"requests\":%d,"
+ "\"heapUsedMb\":%d,\"heapMaxMb\":%d,\"heapPercent\":%.1f,"
+ "\"threads\":%d,\"peakThreads\":%d,\"gcCount\":%d,\"gcTimeMs\":%d}",
status, uptimeSec, REQUESTS.get(),
heap.getUsed() / MB, heap.getMax() / MB, heapRatio * 100,
threads.getThreadCount(), threads.getPeakThreadCount(), gcCount, gcMillis);
}
static void send(HttpExchange exchange, int status, String json) throws IOException {
byte[] body = json.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(status, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
}
}
The watch script:
#!/usr/bin/env bash
# watch-metrics.sh — poll /metrics and alert when the heap status is WARN
URL=${1:-http://127.0.0.1:8080/metrics}
while true; do
json=$(curl -fsS "$URL") || { echo "$(date +%T) DOWN"; sleep 5; continue; }
status=$(echo "$json" | grep -o '"status":"[A-Z]*"' | cut -d'"' -f4)
heap=$(echo "$json" | grep -o '"heapPercent":[0-9.]*' | cut -d: -f2)
echo "$(date +%T) status=$status heap=${heap}%"
if [[ "$status" == "WARN" ]]; then
pid=$(pgrep -f MetricsServer | head -n 1)
jcmd "$pid" GC.class_histogram | head -n 6
break
fi
sleep 5
done
Start the server, check it, send traffic and run the watcher:
java -Xmx128m MetricsServer &
curl -s http://127.0.0.1:8080/metrics
for i in $(seq 1 12); do curl -s -o /dev/null http://127.0.0.1:8080/api/report; done
./watch-metrics.sh
MetricsServer on http://127.0.0.1:8080
{"status":"OK","uptimeSec":1,"requests":0,"heapUsedMb":2,"heapMaxMb":128,"heapPercent":1.6,"threads":9,"peakThreads":9,"gcCount":0,"gcTimeMs":0}
04:49:28 status=WARN heap=86.3%
1185:
num #instances #bytes class name (module)
-------------------------------------------------------
1: 14415 101317864 [B (java.base@21.0.12.1)
2: 13968 335232 java.lang.String (java.base@21.0.12.1)
3: 1943 237816 java.lang.Class (java.base@21.0.12.1)
How it works:
- Health from the inside.
metricsJson()reads heap, GC, thread and uptime data from the MXBeans and returns it as JSON. The same valuesjcmdandjstatshow are now available to any HTTP client, load balancer or dashboard. - A built-in threshold. The endpoint computes
statusitself:WARNabove 80% heap. Monitoring tools only need to read one field. - The leak shows up as growth that never drops. After 12 report requests the heap is at 86%. Garbage collections ran, but they cannot free arrays that
reportCachestill references. - Evidence collected automatically. When the status becomes
WARN, the script runsjcmd GC.class_histogram. The top line,[B(byte arrays) using 101 MB, points straight at code that storesbyte[], which leads toreportCachein/api/report. - Production ready. In the setup from Java Production Setup,
/metricssits behind the same localhost-only Nginx rule as/health/, and the JSON line can also be written through the logger from Java Logging every minute so the history is kept in the logs.