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.GarbageCollectionjdk.JavaMonitorEnterjdk.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
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.
| Tool or API | Since | Best for |
|---|---|---|
-XX:StartFlightRecording | Java 11 in OpenJDK | Recording from start-up, for example in production |
jcmd PID JFR.startJFR.dumpJFR.stop | Java 11 | Starting a recording in a running JVM without a restart |
jdk.jfr.RecordingRecordingFile | Java 11 | Recording and analysing from code, for example in tests |
RecordingStream | Java 14 (JEP 349) | Reacting to events live, inside the application |
jfr printjfr summaryjfr view | Java 11; view | Reading a .jfr |
| JDK Mission Control | Separate download | Graphical analysis of recordings |
All recordings on this page were made with JDK 21. Durations come from Thread.sleep
A custom event, recorded to a file and read back
An order-processing method emits a custom OrderProcessed
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:
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.
andbegin() measure the time between them; an event that is only committed records a point in time.commit() - Annotations shape the event:
gives the type its identifier (by convention a reverse-domain style name),@Name and@Label are for display in tools. Fields of primitive types,@Category ,String andThread are recorded.Class - The file contained both the custom events and
events, read back withjdk.GarbageCollection . For large files, iterate withRecordingFile.readAllEvents andnew RecordingFile(path) instead of loading everything.readEvent() - 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
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:
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
, so fast events are discarded at almost no cost; this is how JFR can watch every lock acquisition but record only contended ones.commit() - A
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,RecordingStream does the same over JMX for another JVM.RemoteRecordingStream - 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.ExecutionSamplejdk.ObjectAllocationSample
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:
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
, 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.countPrimes - The most sampled allocation was
, the JVM's internal name for[B : the backing arrays of the 256-bytebyte[] s and of the strings built from them. Allocation profiles usually point at arrays; the stack trace of each sample says which code made them.StringBuilder - 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()
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):
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
was always false and it removed the allocation and the call. The expensive field was never computed.shouldCommit() - 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
, useshouldCommit() 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.@StackTrace(false)
Recording from the command line
Most production use of JFR needs no code at all. The usual commands are:
records the first minute after start-up;java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar ormaxage=1h instead keeps a rolling window that can be dumped on demand.maxsize=200m starts a recording in a running JVM,jcmd PID JFR.start name=diag settings=profile writes it out, andjcmd PID JFR.dump name=diag filename=diag.jfr ends it.jcmd PID JFR.stop name=diag lists event types and counts;jfr summary app.jfr prints events as text or withjfr print --events jdk.GarbageCollection app.jfr ; and since Java 21,--json orjfr view hot-methods app.jfr print ready-made tables.jfr view gc sets global options such as the repository directory and stack depth; the default stack depth is 64 frames.-XX:FlightRecorderOptions
Some event types are especially useful for modern applications. jdk.VirtualThreadPinnedjdk.JavaMonitorEntersynchronizedjdk.SocketReadjdk.FileReadjdk.ContainerConfigurationjfr metadata
The settings files can be tuned without editing XML. jfr configure method-profiling=high --output my.jfcdefault.jfcjfr help configuregcallocation-profilingexceptionslocking-threshold-XX:StartFlightRecording:method-profiling=high,exceptions=all,filename=app.jfr
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
| Need | Use |
|---|---|
| Always-on diagnostics in production | -XX:StartFlightRecordingmaxagemaxsize |
| Investigating a running JVM | jcmd JFR.startsettings=profileJFR.dump |
| CPU and allocation hot spots | jdk.ExecutionSamplejdk.ObjectAllocationSamplejfr view |
| Business timings next to JVM data | Custom duration events with thresholds |
| Live metrics from events | RecordingStream |
| Assertions about JVM behaviour in tests | RecordingRecordingFile |
| Detailed native and kernel profiling |
See also