JFR and jcmd
- Java course
- Expert
- Lesson 32/46
- 5 min
Learn to profile with Java Flight Recorder and jcmd.
Profiling with JFR
JFR (Java Flight Recorder) collects low-overhead event records from a running application. Method sampling, allocation, garbage collection and lock contention events are recorded. It can run continuously in production.
Recording starts with jcmd PID JFR.start duration=60s filename=rec.jfr. The resulting .jfr file is inspected with jfr print or JDK Mission Control.
The jcmd tool
jcmd is a versatile tool that sends commands to a running JVM. Besides JFR recording it supports heap dumps, thread dumps, GC control and diagnostic commands. jcmd PID help lists the available commands.
After the JFR recording finishes jcmd PID JFR.dump filename=rec.jfr dumps the data. JFR is the first tool to reach for in production issue analysis.
Practice Write the JfrRecorder class
Define class JfrRecorder with a static String start(int pid, int seconds) method that returns "jcmd " + pid + " JFR.start duration=" + seconds + "s". In main print System.out.println(start(1234, 60));.
Starter code
// Define the JfrRecorder class: start method builds the jcmd command
// main: print the command for PID 1234 and 60 secondsSample solution
class JfrRecorder {
static String start(int pid, int seconds) {
return "jcmd " + pid + " JFR.start duration=" + seconds + "s";
}
public static void main(String[] args) {
System.out.println(start(1234, 60));
}
}Expected output
jcmd 1234 JFR.start duration=60s
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the JFR start command
jcmd ____ duration=60s filename=rec.jfr
jcmd JFR.start duration=60s filename=rec.jfr
Explanation: The jcmd JFR.start command starts recording.
2 What is the distinctive advantage of JFR?
- Low overhead Correct answer
- It compiles classes
- It starts threads
- It deletes files
Explanation: JFR can run in production with low overhead.
3 Match the JFR tools
| Term | Meaning |
|---|---|
JFR.start |
Starts recording |
jcmd |
Control tool |
JMC |
Analysis tool |
duration |
Recording length |