Sub topic 6
Recording with Java Flight Recorder
Java Flight Recorder (JFR) is a profiling and event-recording system built into the JVM. This chapter shows how to start a recording, choose its settings, and get a file you can analyze. It assumes you can run Java programs from the command line, read a stack trace, and know what a heap and a thread are. Later chapters cover how to read the results.
Why JFR is the default starting point
JFR records events inside the JVM itself. An event is a small record with a timestamp, a thread, and some data. Examples are a method sample, an object allocation, a garbage collection pause, or a thread waiting on a lock.
JFR has three properties that make it useful:
- Low overhead. The default settings usually cost around 1% of CPU or less. The
profilesettings cost somewhat more, but are still often acceptable in production. - No extra agent. It ships with the JDK. It is free to use in OpenJDK 11 and later.
- Sampling, not instrumentation. It does not rewrite your bytecode. It samples stacks at intervals, so the application runs close to normal speed.
The output is a binary .jfr file. You open it later in JDK Mission Control or read it with the jfr command-line tool.
A program to profile
Use this deliberately slow program. It concatenates strings in a loop. Each s += i allocates a new string and copies all the old characters, so the work grows quickly with the loop length.
import java.util.ArrayList;
import java.util.List;
public class Slow {
public static void main(String[] args) {
long start = System.nanoTime();
for (int round = 0; round < 200; round++) {
String s = "";
for (int i = 0; i < 5_000; i++) {
s += i;
}
if (s.length() == 0) {
System.out.println("unreachable");
}
}
System.out.println((System.nanoTime() - start) / 1_000_000 + " ms");
}
}Compile it and package it as app.jar, or run the class directly with java Slow. The examples below use -jar app.jar. Substitute -cp . Slow if you did not build a JAR.
Starting a recording at launch
The most common way to record is to pass a flag when you start the JVM:
java -XX:StartFlightRecording=duration=60s,filename=app.jfr,settings=profile -jar app.jarThe options are separated by commas:
| Option | Meaning |
|---|---|
| `duration=60s` | Stop recording after 60 seconds and write the file. |
| `filename=app.jfr` | Where to write the recording. |
| `settings=profile` | Use the `profile` configuration instead of `default`. |
If the program exits before the duration ends, JFR does not write the file by default. Add dumponexit=true to write on exit. For a short program like Slow, this is the option you want:
java -XX:StartFlightRecording=filename=slow.jfr,settings=profile,dumponexit=true SlowThe JVM prints a line such as Started recording 1 at startup, and a line naming the file when the recording is written.
Choosing a settings profile
A settings profile is a configuration file that decides which events are enabled and how often they are sampled. The JDK ships two:
| Profile | Use it for | Trade-off |
|---|---|---|
| `default` | Continuous recording in production. | Lowest overhead. Samples Java stacks roughly every 20 ms. |
| `profile` | Short investigations. | Higher overhead. Samples roughly every 10 ms and enables more events, such as more detailed allocation and lock data. |
The sampling interval matters. At 10 ms, a 60-second recording gives about 6,000 samples per thread that is running Java code. That is enough to show the heavy methods but not enough to resolve something that takes 1% of the time in a short run. Record longer, or shorten the interval, when your hot spots are small.
You can also change individual settings on the command line without editing a file:
java -XX:StartFlightRecording=filename=slow.jfr,settings=profile,dumponexit=true,jdk.ObjectAllocationSample#throttle=300/s SlowSettings of the form event#setting=value override the chosen profile for that event. Use jfr print --events or the JMC template manager to see which events and settings exist in your JDK version.
Recording a JVM that is already running
You often cannot restart a production process. Use jcmd to control JFR in a running JVM. First find the process ID with jcmd (with no arguments) or jps.
jcmd <pid> JFR.start name=adhoc settings=profile
jcmd <pid> JFR.dump name=adhoc filename=/tmp/adhoc.jfr
jcmd <pid> JFR.stop name=adhocJFR.startbegins a recording and gives it the nameadhoc.JFR.dumpwrites what has been captured so far to a file. The recording keeps running.JFR.stopends the recording.
Two points about file paths. The file is written by the target JVM, not by jcmd, so the path is resolved on the machine and in the file system of the target process. In a container, that is inside the container. Also, make sure the process user can write to that directory.
You can list active recordings with jcmd <pid> JFR.check.
Continuous recording and the circular buffer
A recording does not have to be time-limited. You can start a recording that keeps only the most recent data, and dump it when something goes wrong. This is sometimes called a flight recorder in the aircraft sense: it is always on, and you read it after an incident.
java -XX:StartFlightRecording=name=always,maxage=15m,maxsize=250M,disk=true -jar app.jarmaxage=15mkeeps about the last 15 minutes of data.maxsize=250Mcaps the disk space that the recording uses.disk=truestores data on disk as it goes, rather than only in memory.
When the data exceeds the limit, the oldest chunks are discarded. When an alert fires, run jcmd <pid> JFR.dump name=always filename=/tmp/incident.jfr to save the window around the problem.
Reading a file without a GUI
On a server with no display, use the jfr tool that ships in the JDK bin directory:
jfr summary slow.jfr
jfr print --events jdk.ExecutionSample slow.jfr
jfr print --events jdk.GarbageCollection slow.jfrjfr summary lists each event type with its count and size. It is the fastest way to confirm that the recording contains what you expect. If jdk.ExecutionSample has a count of zero, no CPU samples were taken and the profile is useless for finding hot methods.
For the Slow program, the top frames of the execution samples should be inside String or StringConcatHelper code, with Slow.main below them. That confirms the profiler found the hot spot you built in.
Common problems
- No file appears. The program exited before
durationended, ordumponexitwas not set. Adddumponexit=true, or usejcmdto dump explicitly. - The file is tiny or empty of samples. The run was too short, or the application was mostly idle. Samples are taken only for threads that are running Java code, so a program waiting on I/O shows few execution samples. Look at the wait and I/O events instead.
- A recording was already running. If you pass
-XX:StartFlightRecordingmore than once, or usejcmdon a JVM that already has a recording, each one needs a uniquename. UseJFR.checkto see what is active. - Profiling a warm-up period. If you record the first seconds of a JVM, the profile shows interpreter and compiler activity, not steady state. For a service, start recording after it has handled traffic for a while.
- Wrong environment. A
profilerecording on a production host with a very high allocation rate can raise overhead noticeably. Start withdefault, and switch only if it lacks detail.
Summary of commands
| Task | Command |
|---|---|
| Record at startup for a fixed time | `-XX:StartFlightRecording=duration=60s,filename=app.jfr,settings=profile` |
| Record a short program until exit | `-XX:StartFlightRecording=filename=out.jfr,dumponexit=true` |
| Start in a running JVM | `jcmd <pid> JFR.start name=adhoc settings=profile` |
| Save the data so far | `jcmd <pid> JFR.dump name=adhoc filename=/tmp/adhoc.jfr` |
| Stop a recording | `jcmd <pid> JFR.stop name=adhoc` |
| List recordings | `jcmd <pid> JFR.check` |
| Inspect a file | `jfr summary file.jfr` |
Exercise
A service has been running for three days and its latency spiked twenty minutes ago. You cannot restart it. What do you do to capture data about the spike, and why might a recording started now miss it?
Show answer
If a continuous recording with maxage was already running (for example maxage=15m or longer), run jcmd <pid> JFR.dump name=<recording> filename=<path> right away, before the old data rolls off. If no recording was running, starting one now with jcmd <pid> JFR.start only captures events from this moment, so it will miss the spike that already happened. It can still help if the spike recurs. The lesson is to run a low-overhead continuous recording with default settings so the data exists when you need it.
Exercise
You run java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar, and the program finishes in 20 seconds. No app.jfr exists. How do you fix it?
Show answer
The recording was still running when the JVM exited, and JFR does not write the file unless told to. Add dumponexit=true to the option list so the recording is written at exit.