Java Flight Recorder

Java Flight Recorder is a profiler and event recorder built into the JVM, cheap enough to leave running in production. It records JVM events such as garbage collections, locks, allocations and CPU samples, and your own application events. This page explains how JFR stores events, defines custom events, writes and reads a recording, streams events live with a threshold, finds the hottest method and the biggest allocator from samples, and measures what an event costs.

Contents

How Java Flight Recorder works

JFR has been part of OpenJDK since Java 11 (JEP 328); before that it was a commercial feature of the Oracle JDK. It records events: small, typed records with a timestamp, the thread, often a stack trace, and fields. The JVM itself defines more than a hundred event types, from jdk.GarbageCollection and jdk.JavaMonitorEnter to periodic samples of CPU, memory and threads, and applications can define their own by extending jdk.jfr.Event.

Its low cost comes from the design. A thread writes events into its own thread-local buffer without locking. Full buffers are moved to global buffers and from there, by a background thread, into chunk files on disk or a ring buffer in memory. Expensive data, such as stack traces and class names, is written once into constant pools and referenced by id. Oracle's troubleshooting guide states that a continuous recording with the default settings generally has no measurable performance effect, and that a profiling recording with default settings costs less than two percent for most applications. The profile.jfc settings collect more detail, for example a CPU sample every 10 ms instead of every 20 ms.

Events come in a few kinds: instant events (something happened), duration events with a start and end that can be filtered by a threshold, sampled events taken at a period such as CPU samples every 20 ms, and periodic events such as CPU load, emitted on a schedule.

Ways to start and read recordings
Tool or APISinceBest for
-XX:StartFlightRecordingJava 11 in OpenJDKRecording from start-up, for example in production
jcmd PID JFR.start, JFR.dump, JFR.stopJava 11Starting a recording in a running JVM without a restart
jdk.jfr.Recording and RecordingFileJava 11Recording and analysing from code, for example in tests
RecordingStreamJava 14 (JEP 349)Reacting to events live, inside the application
jfr print, jfr summary, jfr viewJava 11; view in Java 21Reading a .jfr file on the command line
JDK Mission ControlSeparate downloadGraphical analysis of recordings

All recordings on this page were made with JDK 21. Durations come from Thread.sleep and are rounded down to 10 ms, so the printed values are stable.

A custom event, recorded to a file and read back

An order-processing method emits a custom OrderProcessed event with the order id and item count. Each order sleeps 20 ms per item, so the recorded durations can be checked against the item counts. The program also allocates enough memory to cause garbage collections, and enables the JVM's GC event alongside its own.

Java
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Map;
import java.util.TreeMap;
import jdk.jfr.Category;
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;

public class RecordAndRead {

    // A custom event: fields become columns in the recording
    @Name("demo.OrderProcessed")
    @Label("Order Processed")
    @Category("Demo")
    static class OrderProcessed extends Event {
        @Label("Order Id")
        String orderId;

        @Label("Items")
        int items;
    }

    static void processOrder(int n) throws InterruptedException {
        OrderProcessed event = new OrderProcessed();
        event.begin();                                    // start timing
        event.orderId = "ORD-" + n;
        event.items = n % 5 + 1;
        Thread.sleep(20L * event.items);                  // simulated work
        event.commit();                                   // end timing and record
    }

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("demo", ".jfr");
        try (Recording recording = new Recording()) {
            recording.enable(OrderProcessed.class);
            recording.enable("jdk.GarbageCollection");
            recording.start();

            for (int i = 1; i <= 5; i++) {
                processOrder(i);
            }
            byte[][] garbage = new byte[2000][];
            for (int i = 0; i < garbage.length; i++) {
                garbage[i] = new byte[100000];           // allocate ~200 MB to cause GCs
                garbage[i % 10] = null;
            }
            System.gc();

            recording.stop();
            recording.dump(file);
        }

        Map<String, Integer> counts = new TreeMap<>();
        for (RecordedEvent e : RecordingFile.readAllEvents(file)) {
            counts.merge(e.getEventType().getName(), 1, Integer::sum);
            if (e.getEventType().getName().equals("demo.OrderProcessed")) {
                Duration d = e.getDuration();
                System.out.printf("%s  items=%d  took ~%d ms%n",
                        e.getString("orderId"), e.getInt("items"), d.toMillis() / 10 * 10);
            }
        }
        System.out.println("event types found: " + counts.keySet());
        int gcEvents = counts.getOrDefault("jdk.GarbageCollection", 0);
        System.out.println("GC events recorded: " + (gcEvents > 0));
        System.out.println("recording file size > 0: " + (Files.size(file) > 0));
        Files.delete(file);
    }
}

Output:

Output
ORD-1  items=2  took ~40 ms
ORD-2  items=3  took ~60 ms
ORD-3  items=4  took ~80 ms
ORD-4  items=5  took ~100 ms
ORD-5  items=1  took ~20 ms
event types found: [demo.OrderProcessed, jdk.GarbageCollection]
GC events recorded: true
recording file size > 0: true
  • Each event's duration matches its work: ORD-1 with 2 items took about 40 ms, ORD-4 with 5 items about 100 ms. begin() and commit() measure the time between them; an event that is only committed records a point in time.
  • Annotations shape the event: @Name gives the type its identifier (by convention a reverse-domain style name), @Label and @Category are for display in tools. Fields of primitive types, String, Thread and Class are recorded.
  • The file contained both the custom events and jdk.GarbageCollection events, read back with RecordingFile.readAllEvents. For large files, iterate with new RecordingFile(path) and readEvent() instead of loading everything.
  • The same file opens in JDK Mission Control, where custom events appear under their category next to the JVM's own data.

Streaming events live with a threshold

Four queries take 5, 120, 10 and 80 ms. The event type has a 50 ms threshold, so only the two slow ones should be recorded, and a RecordingStream receives them while the program runs.

Java
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import jdk.jfr.Event;
import jdk.jfr.Name;
import jdk.jfr.Threshold;
import jdk.jfr.consumer.RecordingStream;

public class LiveStream {

    @Name("demo.SlowQuery")
    @Threshold("50 ms")                         // only record queries slower than 50 ms
    static class SlowQuery extends Event {
        String sql;
    }

    static void query(String sql, long ms) throws InterruptedException {
        SlowQuery e = new SlowQuery();
        e.begin();
        Thread.sleep(ms);
        e.sql = sql;
        e.commit();                             // dropped automatically if under the threshold
    }

    public static void main(String[] args) throws Exception {
        CountDownLatch seen = new CountDownLatch(2);
        try (RecordingStream stream = new RecordingStream()) {
            stream.enable(SlowQuery.class).withThreshold(Duration.ofMillis(50));
            stream.onEvent("demo.SlowQuery", e -> {
                System.out.println("live: slow query (" + e.getDuration().toMillis() / 10 * 10
                        + " ms): " + e.getString("sql"));
                seen.countDown();
            });
            stream.startAsync();

            query("SELECT 1", 5);
            query("SELECT * FROM orders", 120);
            query("SELECT id FROM users", 10);
            query("UPDATE stock SET qty = 0", 80);

            seen.await();
        }
        System.out.println("only the 2 queries over 50 ms were reported");
    }
}

Output:

Output
live: slow query (120 ms): SELECT * FROM orders
live: slow query (80 ms): UPDATE stock SET qty = 0
only the 2 queries over 50 ms were reported
  • Only the 120 ms and 80 ms queries reached the handler. The threshold is checked at commit(), so fast events are discarded at almost no cost; this is how JFR can watch every lock acquisition but record only contended ones.
  • A RecordingStream reads events from the recording's in-memory buffers shortly after they are written, typically within a second. It is suited to in-process monitoring, such as counting slow operations and exporting them as metrics. Since Java 16, RemoteRecordingStream does the same over JMX for another JVM.
  • The latch makes the program wait until both events arrived, because streaming is asynchronous; reading right after the last query would miss them.

Profiling with the JVM's own sampling events

JFR's CPU profiler is the jdk.ExecutionSample event: at a fixed period, the JVM records the stack of running threads. Allocation profiling uses jdk.ObjectAllocationSample, a throttled sample of allocations weighted by size. The program runs a CPU-bound prime count and then an allocation-heavy loop, and finds the top entry of each.

Java
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import jdk.jfr.consumer.RecordedFrame;
import jdk.jfr.consumer.RecordingStream;

public class BuiltInEvents {

    static volatile Object sink;

    // CPU-heavy method: should dominate the execution samples
    static int countPrimes(int limit) {
        int c = 0;
        for (int n = 2; n < limit; n++) {
            boolean prime = true;
            for (int d = 2; d * d <= n; d++) {
                if (n % d == 0) {
                    prime = false;
                    break;
                }
            }
            if (prime) {
                c++;
            }
        }
        return c;
    }

    // Allocation-heavy method: should dominate the allocation samples
    static void buildStrings(int n) {
        for (int i = 0; i < n; i++) {
            StringBuilder sb = new StringBuilder(256);
            sb.append("row ").append(i);
            sink = sb.toString();
        }
    }

    static String top(Map<String, Integer> counts) {
        return counts.entrySet().stream().max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey).orElse("-");
    }

    public static void main(String[] args) throws Exception {
        Map<String, Integer> cpu = new ConcurrentHashMap<>();
        Map<String, Integer> alloc = new ConcurrentHashMap<>();
        Map<String, Integer> types = new ConcurrentHashMap<>();
        try (RecordingStream rs = new RecordingStream()) {
            rs.enable("jdk.ExecutionSample").withPeriod(Duration.ofMillis(10));
            rs.enable("jdk.ObjectAllocationSample").with("throttle", "1000/s");
            rs.enable("jdk.GarbageCollection");
            rs.onEvent(e -> types.merge(e.getEventType().getName(), 1, Integer::sum));
            rs.onEvent("jdk.ExecutionSample", e -> {
                RecordedFrame f = e.getStackTrace().getFrames().get(0);    // the top frame
                cpu.merge(f.getMethod().getName(), 1, Integer::sum);
            });
            rs.onEvent("jdk.ObjectAllocationSample", e ->
                    alloc.merge(e.getClass("objectClass").getName(), 1, Integer::sum));
            rs.startAsync();

            System.out.println("primes counted: " + countPrimes(2000000));
            buildStrings(3000000);
            Thread.sleep(1500);                    // let the stream deliver what is buffered
        }
        System.out.println("event types seen: " + types.keySet().stream().sorted()
                .collect(Collectors.joining(", ")));
        System.out.println("hottest method in execution samples: " + top(cpu));
        System.out.println("most sampled allocation:             " + top(alloc));
    }
}

Output:

Output
primes counted: 148933
event types seen: jdk.ExecutionSample, jdk.GarbageCollection, jdk.ObjectAllocationSample
hottest method in execution samples: countPrimes
most sampled allocation:             [B
  • The hottest method was countPrimes, as expected: most samples had it as the top frame. The exact sample counts change with every run, so the program prints only the winner.
  • The most sampled allocation was [B, the JVM's internal name for byte[]: the backing arrays of the 256-byte StringBuilders and of the strings built from them. Allocation profiles usually point at arrays; the stack trace of each sample says which code made them.
  • Sampling at a period, not tracing every call, is what keeps the cost low. JFR samples threads at safepoint-independent points, so it avoids the safepoint bias of profilers built on the standard thread-dump API. For flame graphs from these events, JDK Mission Control or async-profiler's converter can read the same file.

What an event costs

Custom events are meant to stay in production code. The program emits five million events of a type with stack traces disabled, first with no recording running and then with the event enabled, and uses shouldCommit() to skip computing an expensive field when the event would be discarded. Best of 3 runs, a rough comparison.

Java
import jdk.jfr.Event;
import jdk.jfr.Name;
import jdk.jfr.Recording;
import jdk.jfr.StackTrace;

public class EventCost {

    @Name("demo.Tick")
    @StackTrace(false)                        // skip the stack trace: much cheaper
    static class Tick extends Event {
        long value;
    }

    static int expensiveCalls;

    static long expensiveDescription(long v) {
        expensiveCalls++;
        return v * 31;
    }

    // Records n events; the costly field is computed only if the event will be kept
    static long emit(int n) {
        long t0 = System.nanoTime();
        for (int i = 0; i < n; i++) {
            Tick t = new Tick();
            if (t.shouldCommit()) {
                t.value = expensiveDescription(i);
                t.commit();
            }
        }
        return System.nanoTime() - t0;
    }

    public static void main(String[] args) {
        int n = 5000000;
        emit(n);                                       // warm-up while not recording
        expensiveCalls = 0;
        long off = Long.MAX_VALUE;
        for (int r = 0; r < 3; r++) {
            off = Math.min(off, emit(n));
        }
        System.out.printf("no recording:     %5.1f ns per event, expensive field computed %d"
                + " times%n", (double) off / n, expensiveCalls);

        try (Recording rec = new Recording()) {
            rec.enable(Tick.class);
            rec.start();
            expensiveCalls = 0;
            long on = Long.MAX_VALUE;
            for (int r = 0; r < 3; r++) {
                on = Math.min(on, emit(n));
            }
            rec.stop();
            System.out.printf("event enabled:    %5.1f ns per event, expensive field computed"
                    + " %,d times%n", (double) on / n, expensiveCalls);
        }
    }
}

Output (2-CPU Linux machine, JDK 21, best of 3):

Output
no recording:       0.0 ns per event, expensive field computed 0 times
event enabled:     40.8 ns per event, expensive field computed 15,000,000 times
  • With no recording, an event cost effectively nothing: the JIT saw that the event class was disabled, so shouldCommit() was always false and it removed the allocation and the call. The expensive field was never computed.
  • With the event enabled, each event cost tens of nanoseconds, including writing it to the thread's buffer. The expensive field was computed for every event, 15 million times over the three runs.
  • Rules for custom events: put costly field values behind shouldCommit(), use @StackTrace(false) unless you need the call path, give duration events a threshold, and do not emit an event per tiny operation in a hot loop; aggregate and emit one per request or batch instead.

Recording from the command line

Most production use of JFR needs no code at all. The usual commands are:

  • java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar records the first minute after start-up; maxage=1h or maxsize=200m instead keeps a rolling window that can be dumped on demand.
  • jcmd PID JFR.start name=diag settings=profile starts a recording in a running JVM, jcmd PID JFR.dump name=diag filename=diag.jfr writes it out, and jcmd PID JFR.stop name=diag ends it.
  • jfr summary app.jfr lists event types and counts; jfr print --events jdk.GarbageCollection app.jfr prints events as text or with --json; and since Java 21, jfr view hot-methods app.jfr or jfr view gc print ready-made tables.
  • -XX:FlightRecorderOptions sets global options such as the repository directory and stack depth; the default stack depth is 64 frames.

Some event types are especially useful for modern applications. jdk.VirtualThreadPinned (Java 21) records a virtual thread that blocked while pinned to its carrier, with a 20 ms threshold by default. In addition, jdk.JavaMonitorEnter shows contended synchronized blocks; jdk.SocketRead and jdk.FileRead show slow I/O with stack traces; and jdk.ContainerConfiguration records the CPU and memory limits the JVM detected inside a container. Listing all types and their settings on a given JDK is one command: jfr metadata.

The settings files can be tuned without editing XML. jfr configure method-profiling=high --output my.jfc writes a copy of default.jfc with CPU sampling every 10 ms, and jfr help configure lists the other options with their defaults, such as gc, allocation-profiling, exceptions and locking-threshold (20 ms). The same options work directly on the command line, as in -XX:StartFlightRecording:method-profiling=high,exceptions=all,filename=app.jfr. A recording started without a duration, age or size limit is capped at 250 MB by default, as the JVM reports at start-up.

Keeping a low-overhead recording running all the time, with a size or age limit, means that when something goes wrong the data from just before the incident is already there.

Choosing how to use JFR

JFR recipes
NeedUse
Always-on diagnostics in production-XX:StartFlightRecording with maxage or maxsize, dump on incident
Investigating a running JVMjcmd JFR.start with settings=profile, then JFR.dump
CPU and allocation hot spotsjdk.ExecutionSample and jdk.ObjectAllocationSample, viewed in JMC or jfr view
Business timings next to JVM dataCustom duration events with thresholds
Live metrics from eventsRecordingStream
Assertions about JVM behaviour in testsRecording plus RecordingFile
Detailed native and kernel profilingasync-profiler

See also garbage collection for the GC events JFR records, and JVM tuning for acting on what a recording shows.