00:00

Java Flight Recorder (JFR) in Java 11

Last updated: · Standard (Java 11)

Java Flight Recorder (JFR) is a profiling and event-collection framework built into the JVM. It records data such as garbage collections, thread activity and lock contention with very low overhead. Before Java 11 it was a commercial Oracle JDK feature; JEP 328 open-sourced it in OpenJDK 11.

This tutorial shows how to start a recording, how to create your own events with the jdk.jfr API, and how to read the results.

1. Why Is JFR Useful?

Many profilers slow an application down so much that they cannot run in production. JFR is designed to be always on: with the default settings the overhead is typically around 1 percent. When a problem happens, the recording already contains the events that led up to it, which makes production issues much easier to diagnose.

2. Starting a Recording

Commands
# start a recording when the JVM starts, stop after 60 seconds
java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar

# start, dump and stop a recording in a running JVM
jcmd <pid> JFR.start name=live settings=profile
jcmd <pid> JFR.dump name=live filename=live.jfr
jcmd <pid> JFR.stop name=live

Recordings are analysed with JDK Mission Control or with the jdk.jfr.consumer API. The jfr command-line tool for printing recordings was added later, in Java 12.

3. Practical Examples

Example 1: Recording and reading a custom event

The program defines an OrderPlaced event, records three of them with the Recording API, writes a .jfr file and reads it back.

CustomEventRecording.java
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
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 CustomEventRecording {

    // A custom application event; fields become columns in the recording
    @Name("shop.OrderPlaced")
    @Label("Order Placed")
    static class OrderPlaced extends Event {
        @Label("Order Id") String orderId;
        @Label("Amount") double amount;
    }

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("orders", ".jfr");

        try (Recording recording = new Recording()) {
            recording.enable("shop.OrderPlaced");
            recording.start();

            for (int i = 1; i <= 3; i++) {
                OrderPlaced event = new OrderPlaced();
                event.begin();
                event.orderId = "ORD-" + i;
                event.amount = i * 250.0;
                event.commit();                       // written to the recording buffer
            }

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

        // Read the recording back with the jdk.jfr.consumer API
        List<RecordedEvent> events = RecordingFile.readAllEvents(file).stream()
                .filter(e -> e.getEventType().getName().equals("shop.OrderPlaced"))
                .collect(Collectors.toList());
        System.out.println("Events recorded: " + events.size());
        for (RecordedEvent e : events) {
            System.out.println("  " + e.getString("orderId") + " amount=" + e.getDouble("amount"));
        }
        Files.delete(file);
    }
}
Output
Events recorded: 3
  ORD-1 amount=250.0
  ORD-2 amount=500.0
  ORD-3 amount=750.0

Fields of an event class become the event's data. begin() and commit() also record the start time and duration.

Example 2: Recording only slow operations

A threshold tells JFR to keep only events that last longer than a given time, which keeps recordings small while still catching slow operations.

TimedOperation.java
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
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 TimedOperation {

    // begin() and commit() record a start time and a duration for each event
    @Name("shop.ReportExport")
    @Label("Report Export")
    static class ReportExport extends Event {
        @Label("Report") String report;
    }

    static void export(String report, long millis) throws InterruptedException {
        ReportExport event = new ReportExport();
        event.begin();
        Thread.sleep(millis);              // the work being measured
        event.report = report;
        event.commit();
    }

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("export", ".jfr");
        try (Recording recording = new Recording()) {
            // Only keep exports that take at least 100 ms
            recording.enable("shop.ReportExport").withThreshold(Duration.ofMillis(100));
            recording.start();
            export("daily-sales", 20);     // below the threshold: not recorded
            export("annual-audit", 150);   // slow: recorded
            recording.stop();
            recording.dump(file);
        }

        for (RecordedEvent e : RecordingFile.readAllEvents(file)) {
            if (e.getEventType().getName().equals("shop.ReportExport")) {
                System.out.println("Slow export : " + e.getString("report"));
                System.out.println("At least 100 ms: " + (e.getDuration().toMillis() >= 100));
            }
        }
        Files.delete(file);
    }
}
Output
Slow export : annual-audit
At least 100 ms: true

4. How JFR Collects Data

JFR data flow JVM and application events are written to thread-local buffers, collected into global buffers, written to a .jfr file, and analysed with JDK Mission Control or the consumer API. Events JVM + custom events thread buffers cheap, lock-free writes .jfr file binary recording Analysis JMC or jdk.jfr.consumer
Figure 1: Events are buffered per thread, which keeps the overhead low enough for production use.

5. Important Points and Best Practices

  • Use the built-in default settings for always-on recording and profile for short, detailed investigations.
  • Keep custom events small and only enable the ones you need.
  • Set maxage or maxsize for continuous recordings so files do not grow without limit.
  • Since Java 14, JFR event streaming (JEP 349) lets an application consume events while they are recorded.

6. Summary

  • JFR is a low-overhead event recorder built into the JVM.
  • It was open-sourced in OpenJDK 11 through JEP 328.
  • Start it with -XX:StartFlightRecording or jcmd JFR.start.
  • Custom events extend jdk.jfr.Event, and recordings can be read with jdk.jfr.consumer.

Related Tutorials

7. References