Skip to lesson

VisualVM and JDK Mission Control

Command-line tools give you numbers; graphical tools let you watch a program live and look back at what it did. VisualVM shows a running JVM as live graphs, and Java Flight Recorder records what happened inside the JVM into a file that JDK Mission Control can explain to you later.

VisualVM: monitor, sampler and heap dump viewer

VisualVM is a free desktop tool that connects to running JVMs and shows them as live graphs. Since JDK 9 it is not part of the JDK; download it from its official site, visualvm.github.io, unzip it and start it.

Terminal
# start VisualVM with a chosen JDK (folder names are examples)visualvm --jdkhome "C:\Program Files\Java\jdk-21"# open a heap dump straight awayvisualvm --openfile results.hprof

Local Java programs appear in its Applications list by themselves, through the same attach mechanism jcmd uses. Double-click a program to open its tabs:

  • Monitor: graphs of CPU, heap and metaspace, loaded classes and threads, plus buttons to run a GC and take a heap dump. A heap graph whose lowest points keep rising is the same leak signal as OU in jstat.
  • Threads: a timeline of every thread's state, and a button for a thread dump.
  • Sampler: CPU sampling (which methods are running most often) and memory sampling (which classes take the most space, updated live).

VisualVM also opens .hprof heap dumps and shows classes, instances and their references, so it can stand in for a dump analyser on small dumps.

Sampling is light enough for a test server. VisualVM's Profiler tab (instrumenting every method) is much heavier; avoid it on production.

Java Flight Recorder: low-overhead recording built into the JDK

Java Flight Recorder (JFR) is a low-overhead event recorder built into the JVM. It saves GC, allocation, thread and custom events to a .jfr file for later analysis.

Java Flight Recorder (JFR) is a recorder built into HotSpot.

Example 1 · Your own JFR events, recorded and read back

StoreOrderRecordingDemo.javaJava
import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import jdk.jfr.Event;import jdk.jfr.Label;import jdk.jfr.Name;import jdk.jfr.Recording;import jdk.jfr.consumer.RecordedEvent;import jdk.jfr.consumer.RecordingFile;
@Name("demo.OrderPlaced")@Label("Order Placed")class OrderPlacedEvent extends Event {    @Label("Product")    String product;
    @Label("Amount in rupees")    int amount;}
public class StoreOrderRecordingDemo {    public static void main(String[] args) throws Exception {        Path dir = Files.createTempDirectory("jfr-demo");        Path file = dir.resolve("orders.jfr");
        try (Recording recording = new Recording()) {            recording.enable("demo.OrderPlaced");            recording.start();
            String[] products = {"Laptop", "Keyboard", "Mouse"};            int[] amounts = {52000, 1800, 650};            for (int i = 0; i < products.length; i++) {                OrderPlacedEvent event = new OrderPlacedEvent();                event.product = products[i];                event.amount = amounts[i];                event.commit();                     // write the event into the recording            }
            recording.stop();            recording.dump(file);        }
        List<RecordedEvent> events = RecordingFile.readAllEvents(file);        System.out.println("Recording file: " + file.getFileName());        System.out.println("Events read back: " + events.size());        for (RecordedEvent e : events) {            System.out.println(e.getEventType().getName() + " -> "                    + e.getString("product") + ", Rs " + e.getInt("amount"));        }
        Files.delete(file);        Files.delete(dir);    }}
Output
Recording file: orders.jfr
Events read back: 3
demo.OrderPlaced -> Laptop, Rs 52000
demo.OrderPlaced -> Keyboard, Rs 1800
demo.OrderPlaced -> Mouse, Rs 650

What this code does

  • OrderPlacedEvent extends jdk.jfr.Event; @Name is its event type and @Label the text JMC shows. Each commit() writes one event, with its fields and a timestamp, into the recording.
  • The Recording API starts and stops a recording from inside the program and dump writes the .jfr file. RecordingFile.readAllEvents reads it back; JMC and jfr print read the same file.
  • Only the custom event is enabled here, so the file holds exactly three events and the output is the same on every run. A real recording enables the JVM's built-in events too.

While the program runs, it writes small events into a buffer: each GC and its pause, samples of which methods are running, samples of where objects are allocated, lock waits, file and socket reads, exceptions, thread starts and more. At the end you get one .jfr file. JFR is designed to stay on in production: with the default settings its overhead is usually around 1% or less. settings=profile records more detail for a somewhat higher cost. JFR was a paid Oracle feature in JDK 8; it is free and open source in OpenJDK 11 and later, and was later backported to OpenJDK 8u262. Your own code can add events too: extend jdk.jfr.Event, set its fields and call commit(). They appear in the same recording, next to the JVM's GC and allocation events.

Starting a recording: -XX:StartFlightRecording or jcmd JFR.start

Two ways start a recording. At start-up, -XX:StartFlightRecording with options such as duration=60s and filename=app.jfr records from the first second. On a program that is already running, jcmd <pid> JFR.start starts one without a restart.

Example 2 · Record from start-up

Terminal
java -XX:StartFlightRecording=duration=20s,filename=results.jfr ResultsServer
Sample output
[0.961s][info][jfr,startup] Started recording 1. The result will be written to:
[0.961s][info][jfr,startup]
[0.961s][info][jfr,startup] C:\...\results.jfr
Results server started. Running for 90 seconds.

What this code does

  • ResultsServer from the jps and jcmd lesson, on JDK 21. JFR starts in under a second and prints where it will write the file (the folder is shortened with ...). After 20 seconds the recording stops and the file is written; the program keeps running.
  • Use duration for a fixed window, or maxsize/maxage for a continuous recording you dump when needed.

Example 3 · Start, check, dump and stop a recording with jcmd

Terminal
jcmd <pid> JFR.start name=leak settings=profilejcmd <pid> JFR.checkjcmd <pid> JFR.dump name=leak filename=leak.jfrjcmd <pid> JFR.stop name=leak
Sample output
23892:
Started recording 2. No limit specified, using maxsize=250MB as default.

Use jcmd 23892 JFR.dump name=leak filename=FILEPATH to copy recording data to file.

23892:
Recording 1: name=1 duration=30s (running)

Recording 2: name=leak maxsize=250.0MB (running)

23892:
Dumped recording "leak", 278.1 kB written to:

C:\...\leak.jfr

23892:
Stopped recording "leak".

What this code does

  • This ResultsServer was already recording from start-up (recording 1), so JFR.check lists two. Several recordings can run at once.
  • JFR.dump wrote the 10 seconds recorded so far (278 kB) while the recording continued; JFR.stop ended it. The JVM itself writes the file, so a relative name lands in the program's working folder.

With jcmd, a recording has a name you choose. JFR.check lists recordings, JFR.dump name=... filename=... copies what has been recorded so far into a file while it keeps recording, and JFR.stop name=... ends it. Without a duration or size limit, JDK 21 keeps at most 250 MB of data and says so. A good habit on a service is a continuous recording with a size limit, for example -XX:StartFlightRecording=maxsize=200m,filename=/var/jfr/app.jfr, and a JFR.dump when something goes wrong: you get the minutes before the problem, not after.

Opening a recording in JDK Mission Control

JDK Mission Control (JMC) is the desktop tool for reading .jfr files. Like VisualVM it is a separate download, from jdk.java.net/jmc or from your JDK vendor.

Example 4 · Read a recording with the jfr tool

Terminal
jfr summary results.jfrjfr view gc results.jfrjfr view allocation-by-class results.jfrjfr view hot-methods results.jfr
Sample output
 Version: 2.1
 Chunks: 1
 Start: 2026-10-15 18:23:40 (UTC)
 Duration: 21 s

 Event Type                              Count  Size (bytes)
=============================================================
 jdk.GCPhaseParallel                       924         20775
 jdk.BooleanFlag                           500         14740
...

                                Garbage Collections

Start    GC ID Type                     Heap Before GC Heap After GC Longest Pause
-------- ----- ------------------------ -------------- ------------- -------------
23:53:40     0 Young Garbage Collection        23.0 MB        3.0 MB       17.5 ms
23:53:43     1 Young Garbage Collection        35.0 MB        7.0 MB       14.2 ms
23:53:50     2 Young Garbage Collection        73.0 MB       13.1 MB       10.4 ms
23:53:56     3 Young Garbage Collection        74.1 MB       19.9 MB       8.31 ms

                                  Allocation by Class

Object Type                                                         Allocation Pressure
------------------------------------------------------------------- -------------------
byte[]                                                                           38.05%
java.lang.String                                                                 37.07%
java.lang.Object[]                                                               15.22%
java.util.concurrent.ConcurrentHashMap$Node[]                                     9.46%
...

                                    Java Methods that Executes the Most

Method                                                                                     Samples Percent
------------------------------------------------------------------------------------------ ------- -------
java.lang.Integer.getChars(int, int, byte[])                                                     3  50.00%
ResultsServer.servePage(int)                                                                     2  33.33%
...

What this code does

  • The 20-second recording of ResultsServer (JDK 21; jfr view is new in JDK 21). The gc view already tells the leak story: "Heap After GC" grows 3.0, 7.0, 13.1, 19.9 MB.
  • allocation-by-class shows where new memory goes: byte[] and String from building page lines and sessions. High allocation is not the same as a leak, but it explains frequent young GCs.
  • hot-methods is based on only 6 samples here, because the program sleeps most of the time; on a busy service you get thousands. JMC shows the same data as pages and graphs.

Example 5 · Print the raw events of one type

Terminal
jfr print --events jdk.GarbageCollection results.jfr
Sample output
jdk.GarbageCollection {
  startTime = 23:53:40.585 (2026-10-15)
  duration = 17.5 ms
  gcId = 0
  name = "G1New"
  cause = "G1 Evacuation Pause"
  sumOfPauses = 17.5 ms
  longestPause = 17.5 ms
  eventThread = "VM Thread" (osThreadId = 27900)
}

jdk.GarbageCollection {
  startTime = 23:53:43.764 (2026-10-15)
  duration = 14.2 ms
  gcId = 1
  name = "G1New"
...

What this code does

  • Every event has a type, a start time, often a duration, and its own fields. G1New is G1's young collector; the cause and pause times match the gc view above.
  • jfr print --json gives the same data as JSON, which is handy for scripts. JMC's Event Browser shows these events as a table.

Open the file and start with the Automated Analysis Results page: JMC runs rules on the recording and colours each finding by how serious it is, such as long GC pauses, heavy allocation or lock contention. Then go deeper: the Memory and Garbage Collections pages show heap use and every pause, Method Profiling shows the hottest methods, and the Event Browser lists every event type with its fields. Your own events appear there under their label. The JDK also has a command-line reader, jfr: jfr summary counts events, jfr print --events <type> prints them, and on JDK 21 jfr view prints ready-made tables such as gc, gc-pauses, allocation-by-class and hot-methods.

A recording also stores system properties and environment variables, which can include secrets. Share it like a heap dump: restricted. On JDK 19 and later, jfr scrub --exclude-events jdk.InitialEnvironmentVariable,jdk.InitialSystemProperty in.jfr out.jfr removes them.

Next step

Check your understanding

11 quick questions