Sub topic 15
Writing reliable microbenchmarks with JMH
This chapter assumes you can build a Maven project and run a jar from the command line. It also assumes you know the JIT basics from the previous chapter: code starts interpreted, hot methods get compiled, and the compiler optimizes aggressively. A hand-written timing loop usually fights those facts. JMH (the Java Microbenchmark Harness, maintained by the OpenJDK project) is built to work with them.
When a microbenchmark is the right tool
A microbenchmark measures one small piece of code in isolation, such as a parsing routine, a data structure operation or a string join. Use one to compare two implementations after a profiler has pointed at a hot method. Do not use one to find the bottleneck. A profile of the real application shows where time goes. A microbenchmark only shows how fast an isolated piece runs.
Why a hand-written loop lies
The System.nanoTime() loop from the earlier Slow example looks reasonable, but it has several problems:
- No warmup. The first iterations run in the interpreter or in lightly optimized code, so they measure startup, not steady state.
- Dead-code elimination. If the result is never used, the JIT compiler may delete the computation, and you time an empty loop.
- Constant folding. If the inputs are compile-time constants, the compiler may compute the answer once, at compile time.
- Profile pollution. The JIT specializes code using what it has seen. Running benchmark A before benchmark B in one JVM can change how B is compiled.
- Noise. Garbage collection, CPU frequency changes and other processes add variation that one run cannot reveal.
JMH addresses each of these with warmup phases, forked JVMs, controlled state and a way to consume results.
Setting up a project
The simplest start is the official Maven archetype. It produces a project whose build creates a self-contained benchmarks.jar.
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DgroupId=org.sample -DartifactId=benchmarks -Dversion=1.0
cd benchmarks
mvn clean verify
java -jar target/benchmarks.jarAlways run benchmarks from this jar and not from your IDE's run button. The build step runs JMH's annotation processor, which generates the code that drives each benchmark. Without it, nothing is generated.
Anatomy of a benchmark
This is the benchmark from the plan, which compares two ways of joining strings.
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
public class ConcatBenchmark {
private String a = "hello";
private String b = "world";
@Benchmark
public String plus() {
return a + b;
}
@Benchmark
public String builder() {
return new StringBuilder().append(a).append(b).toString();
}
}Each annotation controls one part of the run:
| Annotation | What it controls |
|---|---|
| `@Benchmark` | Marks a method that JMH calls repeatedly and times. |
| `@State(Scope.Thread)` | Gives each benchmark thread its own instance of the class, which holds the inputs. |
| `@BenchmarkMode` | What is reported: `AverageTime`, `Throughput`, `SampleTime` (a distribution with percentiles) or `SingleShotTime`. |
| `@Warmup` | Iterations run and discarded so the JIT can reach steady state. |
| `@Measurement` | Iterations whose results are reported. |
| `@Fork` | How many fresh JVMs run the whole benchmark. |
The fields a and b are non-final instance fields in a @State class. This is deliberate. A static final constant could be folded at compile time, and the benchmark would measure nothing.
How a run proceeds
Forking matters because each fork starts with no JIT history, so one benchmark cannot influence the compilation of another. Two forks also expose run-to-run variation that a single JVM would hide, for example when one fork happens to inline a method differently.
Dead-code elimination and the Blackhole
JMH consumes the return value of a @Benchmark method, so returning a result keeps the computation alive. If a method produces several values, feed them to a Blackhole.
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Thread)
public class DeadCodeBenchmark {
private double x = Math.PI;
@Benchmark
public void deadCode() {
Math.log(x); // result unused: may be eliminated
}
@Benchmark
public double returned() {
return Math.log(x); // JMH consumes the return value
}
@Benchmark
public void blackhole(Blackhole bh) {
bh.consume(Math.log(x));
bh.consume(Math.sqrt(x));
}
}Run all three. deadCode will usually report a time near zero, which is a sign that it measured nothing. If a result looks too good to be true, suspect elimination or constant folding.
State, parameters and setup
Use @Setup for work that should not be timed, such as building input data. @Param runs the same benchmark across several input values, which shows how cost grows with size.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(2)
public class SumBenchmark {
@Param({"100", "10000"})
private int size;
private List<Integer> list;
@Setup
public void setup() {
list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(i);
}
}
@Benchmark
public long sum() {
long total = 0;
for (int v : list) {
total += v;
}
return total;
}
}@Setup runs once per trial by default, which is once per fork. Use @Setup(Level.Invocation) only when the benchmark mutates its state. It adds timing overhead that can swamp fast methods.
Reading the results
JMH prints a score and an error for each benchmark:
Benchmark Mode Cnt Score Error Units
ConcatBenchmark.plus avgt 10 12.345 ± 0.210 ns/op
ConcatBenchmark.builder avgt 10 15.012 ± 0.340 ns/opThe numbers above only show the format. Your values will differ. The error is a 99.9% confidence interval across all measured iterations. If two intervals overlap, you have not shown a difference. Increase iterations or forks, or accept that the two implementations perform the same.
JMH also prints a warning that its results are not a proof of performance. Treat scores as relative within one machine, JDK and configuration. A benchmark that wins by 5 ns here says little about the full application.
Profilers inside JMH
JMH can attach profilers to explain a score and not just report it. Pass them with -prof:
java -jar target/benchmarks.jar ConcatBenchmark -prof gc
java -jar target/benchmarks.jar ConcatBenchmark -prof stackThe gc profiler reports allocation per operation (gc.alloc.rate.norm, in bytes). This often explains why one variant is faster: it allocates less, so it causes less GC pressure. The stack profiler samples thread stacks to show where time goes inside the benchmark.
Common mistakes
- Benchmarking with too few forks, then trusting a difference inside the error margin.
- Using loops inside a
@Benchmarkmethod to "repeat" work. The JIT can unroll or hoist the loop. Let JMH call the method repeatedly. - Comparing results from different machines, JDKs or power settings.
- Running benchmarks while other heavy processes use the CPU.
- Measuring something the real application never does, such as perfectly predictable inputs that make branches look cheap.
Exercise
A benchmark method public void test() { Math.sqrt(value); } reports 0.3 ns/op, where value is a field. What is probably wrong, and how do you fix it in two different ways?
Show answer
The result of Math.sqrt is unused, so the JIT compiler likely eliminated the call as dead code, and the score reflects an empty method. Fix it by returning the value (public double test() { return Math.sqrt(value); }), or by taking a Blackhole parameter and calling bh.consume(Math.sqrt(value)).
Exercise
Why does @Fork(2) give more trustworthy results than running 10 measurement iterations in a single JVM?
Show answer
Each fork starts a fresh JVM with no JIT history, so earlier code cannot shape how the benchmark is compiled. Two forks also reveal variation between JVM runs, such as different inlining decisions, which a single JVM would hide.