Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 13 / Topic 7 of 8

Observing a running JVM from the outside

Everything so far ran inside the program being measured. jcmd and jstat (both ship with the JDK) inspect a running JVM process from a second terminal, with nothing to add to the program itself beyond letting it run long enough to inspect.

System.out.println("PID: " + ProcessHandle.current().pid());
Thread.sleep(20_000);   // give a second terminal time to look
# terminal 1
$ javac LongRunningForJcmd.java
$ java LongRunningForJcmd
PID: 16796
Holding 20000 byte[512] arrays; sleeping 20s for inspection...

# terminal 2, while it's still sleeping
$ jcmd 16796 VM.version
16796:
OpenJDK 64-Bit Server VM version 21.0.11+10-LTS
JDK 21.0.11

$ jcmd 16796 GC.heap_info
16796:
 garbage-first heap   total 794624K, used 15887K [0x0000007000800000, 0x0000007300800000)
  region size 8192K, 2 young (16384K), 0 survivors (0K)
 Metaspace       used 423K, committed 576K, reserved 1114112K
  class space    used 30K, committed 128K, reserved 1048576K

$ jstat -gc 16796
    S0C    S1C    S0U    S1U      EC       EU        OC       OU    MC    MU   CCSC  CCSU  YGC  YGCT  FGC  FGCT  CGC  CGCT   GCT
     0.0    0.0    0.0    0.0  32768.0   8192.0  753664.0     0.0   0.0   0.0   0.0   0.0    0 0.000    0 0.000    0 0.000  0.000

jcmd <pid> VM.version and GC.heap_info need nothing more than the process ID — no flags set when the program started, no code changed. GC.heap_info shows the G1 heap's current size and how much is actually used (around 15–16 MiB here, matching the ~10 MiB of byte[512] arrays the program deliberately keeps reachable, plus JVM overhead); Metaspace is the separate region holding loaded class metadata, not objects. jstat -gc prints the same kind of numbers in one compact row meant for repeated sampling — EC/EU are the young generation's (Eden's) capacity and current use, YGC is how many young-generation collections have run so far.

Tool What it's for
jcmd <pid> help lists every diagnostic command a given JVM supports
jcmd <pid> VM.version, VM.flags which JVM, and which flags it's actually running with
jcmd <pid> GC.heap_info a heap summary, on demand, from outside the process
jcmd <pid> Thread.print every thread's state and stack — the real tool for diagnosing a deadlock (Part 12) in a live service
jstat -gc <pid> one row of GC/heap numbers, good for sampling repeatedly
jps lists running JVM processes and their PIDs, so you don't have to hunt for one by hand

Full program: examples/LongRunningForJcmd.java.

Done here? The practice set for Part 13 — including the solutions — is on the part page.

Search the guide