Profiling Tools
You cannot optimize what you cannot measure. In the world of high-performance Java, guessing is a recipe for disaster. While tools like VisualVM are great for local development, production profiling requires tools that are low-overhead, accurate, and always-on.
1. JDK Flight Recorder (JFR)
JFR is a profiling and event collection framework built directly into the JVM. It is designed to run in production with less than 1% overhead.
Think of JFR as the “Black Box” of an airplane. It continuously records events (GC pauses, method latency, lock contention, network I/O) into a circular buffer.
Key Features
- Low Overhead: Uses thread-local buffers and emits events directly from the JVM kernel.
- Deep Insight: Sees things OS tools miss (e.g., “Blocked on Monitor Enter”).
- Continuous: Can be configured to keep the last 1 hour of data in memory/disk.
How to use it
Start recording (Command Line):
java -XX:StartFlightRecording:filename=recording.jfr,duration=60s -jar myapp.jar
2. Async Profiler & Safepoint Bias
Traditional profilers (like VisualVM’s sampler) suffer from Safepoint Bias. They can only sample threads when they are at a “Safe Point” (e.g., end of a loop). If your code is stuck in a long loop or a native call without safepoints, the profiler will be blind to it.
Async Profiler uses OS-level capabilities (perf_events on Linux) to sample the CPU at random intervals, regardless of JVM state. This provides the ground truth of CPU usage.
3. Flame Graphs
The output of Async Profiler is typically a Flame Graph.
- X-Axis: Population (how often a method was on the CPU). Wider = More CPU time.
- Y-Axis: Stack Depth.
- Color: Usually random, or color-coded by package.
[!TIP] Look for the Plateaus: Wide, flat bars at the top of the flame graph represent methods that are burning CPU but not calling anything else. These are your optimization targets.
4. Interactive: Flame Graph Explorer
Hover over the blocks to identify the performance bottleneck.
5. Summary
- JFR is your continuous flight recorder.
- Async Profiler avoids Safepoint Bias.
- Flame Graphs make CPU hotspots obvious.