Profiling and allocation analysis
What you will learn
Profiling explains where time and memory go. CPU samples, allocation samples, GC events, lock waits and I/O durations answer different questions. Record only an owned JVM, with bounded duration and size, separately from unprofiled timing.
- Distinguish allocation rate from retained heap.
- Choose evidence for CPU, blocking and allocation hypotheses.
- Read a local JFR recording without interpreting samples as exact counts.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Standalone Java 21 functional examples; measurements are separate. JMH is source-reviewed, not executed.
Normalize synthetic allocation counters
public class Main { static long bytesPerOp(long bytes,long operations) { if(bytes<0||operations<=0) throw new IllegalArgumentException(); return bytes/operations; } public static void main(String[] args) { System.out.println(bytesPerOp(8192,16)); }}Expected output:
5128,192 fictional bytes across 16 operations. Integer division truncates fractional values.
Follow the bottleneck
High CPU with hot stacks suggests CPU work. Low CPU and high latency may indicate socket waits, database calls, pool contention or locks. JFR execution samples, thread park/monitor events, GC pauses and allocation samples help test hypotheses. Sampling misses work and cannot establish cause on its own.
Allocation and retention
Short-lived objects can increase allocation pressure without increasing live heap. Retention depends on reachability; heap dumps may contain secrets. Sample counts are not exact allocation counts. JMH -prof gc can report allocation metrics; JFR can locate allocation sites. async-profiler requires reviewed native tooling and permissions and is not run.
Owned-process recording
The companion runs a separate JVM with -XX:StartFlightRecording=filename=profile.jfr,settings=profile,dumponexit=true,maxsize=8m and reads jfr summary. Profiling can affect timing. The custom event below checks the JFR pipeline, not CPU sampling accuracy.
Record and read a custom JFR event
public class Main { @jdk.jfr.Name("tutorial.PerfWork") static class Work extends jdk.jfr.Event { int items; } public static void main(String[] args) { try { var path=java.nio.file.Files.createTempFile("byte-mind-", ".jfr"); try { try(var recording=new jdk.jfr.Recording()) { recording.enable(Work.class); recording.start(); Work event=new Work(); event.items=7; event.commit(); recording.stop(); recording.dump(path); } var events=jdk.jfr.consumer.RecordingFile.readAllEvents(path); System.out.println(events.stream().filter(e->e.getEventType().getName().equals("tutorial.PerfWork")).mapToInt(e->e.getInt("items")).sum()); } finally { java.nio.file.Files.deleteIfExists(path); } } catch(java.io.IOException e) { throw new java.io.UncheckedIOException(e); } }}Expected output:
7The test-owned recording contains a custom event; temporary file cleanup is explicit.
Distinguish allocated and retained payload
public class Main {
public static void main(String[] args) { long allocated=0; byte[][] retained=new byte[2][]; for(int i=0;i<8;i++){byte[] b=new byte[1024];allocated+=b.length;retained[i%2]=b;} System.out.println(allocated); System.out.println(retained[0].length+retained[1].length); }}Expected output:
81922048Logical payload sizes, not actual heap measurements; headers, optimization and GC timing excluded.
Common mistakes
Do not use freeMemory as an allocation counter, infer a leak from allocation rate alone, or attach to unrelated JVMs.
Practice
Given fictional counters 3,600 bytes and 12 operations, print 300 bytes per operation. Reject nonpositive operations.
Expected output:
300Compare with the manual review criteria.
Further reading: JFR · Diagnostics. Independent editorial review remains pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Profiling and allocation analysis — knowledge check
Performance engineering reasoning.
A JFR allocation sample names a method. What can it support?
Requests stall while CPU usage is low and threads appear blocked. Which evidence tests a lock-wait hypothesis?
Why record a profiling run separately from an unprofiled timing run?
Two retained byte arrays each have payload length 1,024. What does 2,048 represent?
A learner wants to inspect JVMs on a shared host. What is the approved scope of this lab?