Sub topic 3
Heap Dumps, Contention, and Reliable Performance Measurements
Assume you know basic Java, can run commands, and understand threads, stack traces, and the heap. This chapter focuses on finding memory leaks and avoiding misleading measurements.
Heap dumps and memory leaks
A heap dump is a snapshot of objects currently in the JVM heap. Capture one when memory remains high after garbage collection:
jcmd <pid> GC.heap_dump /tmp/app.hprofOpen the file in Eclipse MAT or another memory analyzer. Start with the dominator tree. It shows which objects retain the most memory. A leak often appears as a collection that keeps growing because a long-lived object still references its entries.
A heap dump is large and can pause or slow an application. Capture it only when needed, and protect it because it may contain user data.
Thread dumps and lock contention
A thread dump shows each thread's state and stack:
jcmd <pid> Thread.print > threads.txtLook for many threads in BLOCKED, or for repeated stack traces waiting on the same monitor. Java Flight Recorder can add lock-wait duration and owning-thread information, which is useful when a short synchronized section becomes a throughput bottleneck.
JIT compilation and warmup
The just-in-time (JIT) compiler converts frequently executed bytecode into optimized machine code. Early timings may include interpretation and compilation, so a program can become faster after warmup. This effect makes one-shot timing unreliable.
Reliable microbenchmarks with JMH
JMH, the Java Microbenchmark Harness, performs warmup, measurement, and JVM forking for you. It also uses returned results to reduce dead-code elimination:
@Benchmark
public String join() {
return new StringBuilder().append("hello").append("world").toString();
}Put this method in a JMH benchmark class with @Warmup, @Measurement, and @Fork annotations, then compare it with a competing implementation. Benchmark realistic inputs and inspect variance, not only the average.
Change one thing, then measure again
Use a repeatable loop:
- Define the symptom and metric, such as p99 latency or allocation rate.
- Record a baseline under the same workload.
- Change one relevant thing.
- Run the same workload and compare the result.
- Keep the change only if the target improves without unacceptable regressions.
Profiling safely in production
Prefer low-overhead tools such as JFR with a bounded recording:
java -XX:StartFlightRecording=duration=60s,filename=app.jfr,settings=profile -jar app.jarAvoid heap dumps during peak traffic unless the incident justifies the risk. Remove sensitive recordings and dumps after analysis.
Exercise
Why should a benchmark include warmup iterations?
Show answer
Warmup lets the JIT compile and optimize hot code before measurements begin.