Video in progress

What is Java Flight Recorder (JFR), and how do you turn it on?

JFR is a very low-overhead recorder built into the JVM: it writes events like GC, allocation, locks, I/O and CPU sampling to a .jfr file. You turn it on with the -XX:StartFlightRecording flag, or on a running process with jcmd <pid> JFR.start.

📖 Answer

JFR used to be a commercial Oracle feature. Since Java 11 it is free and open in OpenJDK. With the default settings the overhead is around 1%, which is why people use it on prod too.

Turning it on from startup:

java -XX:StartFlightRecording=duration=5m,filename=/tmp/app.jfr -jar app.jar

On a running service:

jcmd 12345 JFR.start name=slow duration=2m filename=/tmp/slow.jfr
jcmd 12345 JFR.dump name=slow      # take the recording as it is so far
jcmd 12345 JFR.stop name=slow

You open the file in JDK Mission Control (JMC): which methods eat CPU, where lots of objects are created, which lock the threads are waiting on, how long the GC pauses are.

For a quick look in the terminal there is the jfr tool:

jfr summary /tmp/app.jfr
jfr print --events jdk.GarbageCollection /tmp/app.jfr | head

In practice, when the situation is "the service is sometimes slow and we don't know why", the first thing I do is a 5-minute JFR recording.