Java Flight Recorder (JFR) in 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
# 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.
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);
}
}
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.
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);
}
}
Slow export : annual-audit At least 100 ms: true
4. How JFR Collects Data
5. Important Points and Best Practices
- Use the built-in
defaultsettings for always-on recording andprofilefor short, detailed investigations. - Keep custom events small and only enable the ones you need.
- Set
maxageormaxsizefor 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:StartFlightRecordingorjcmd JFR.start. - Custom events extend
jdk.jfr.Event, and recordings can be read withjdk.jfr.consumer.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What is Java Flight Recorder?
A diagnostic and profiling tool built into the JVM that records JVM and application events with low overhead into .jfr files.
Q2. Is JFR free to use?
Yes. Since OpenJDK 11 (JEP 328), JFR is part of the open-source JDK and free to use, including in production.
Q3. How do I start JFR for a running application?
Use jcmd <pid> JFR.start, then JFR.dump to write a file and JFR.stop to end the recording.
Q4. How do I create a custom JFR event?
Extend jdk.jfr.Event, add fields, then create an instance, call begin(), set the fields and call commit().