Sub topic 3
What JMH does for you
This chapter assumes you know basic Java and annotations, can run Maven from a terminal, and have a general idea that the JVM compiles hot code at runtime. The previous chapters covered why hand-written timing loops mislead and how warmup and JIT compilation affect them. This chapter shows how the Java Microbenchmark Harness (JMH) deals with those problems. It also covers which problems JMH leaves to you.
What JMH is
JMH is a benchmarking framework maintained by the OpenJDK project and written by the same engineers who work on the JVM. It is a library plus an annotation processor. You write ordinary Java methods and mark them with @Benchmark. At build time, the processor generates extra classes that contain the real measurement code. At run time, a launcher starts fresh JVMs, runs those generated classes, and reports statistics.
The central idea is that you describe what to measure, and JMH controls how it is measured. Most benchmark mistakes come from the "how", so moving that part into a tested harness removes whole categories of errors.
The problem, restated in code
Here is the kind of loop JMH replaces:
public class NaiveTiming {
public static void main(String[] args) {
int[] data = new int[10_000];
long total = 0;
long start = System.nanoTime();
for (int i = 0; i < 1_000; i++) {
for (int value : data) {
total += value;
}
}
long elapsed = System.nanoTime() - start;
System.out.println(total);
System.out.println(elapsed / 1_000 + " ns per call");
}
}This program measures one run in one JVM. The first iterations run in the interpreter. The JIT compiler may replace the code part-way through the loop, using on-stack replacement. The loop is also written inside main, which is a different compilation context from the one a real caller would produce. Running it three times can give three different answers, and nothing in the output tells you which one to trust.
What JMH controls
The table lists the jobs JMH takes over and the mechanism it uses for each.
| Problem | What JMH does |
|---|---|
| Interpreter and JIT warmup | Runs warmup iterations whose results are discarded, then measurement iterations. |
| One JVM's luck (JIT decisions, memory layout, profile pollution) | Runs each benchmark in separate forked JVMs and combines the results. |
| Loop-related optimizations around your code | Generates the measurement loop in a separate class, and keeps your method out of `main`. |
| Dead-code elimination | Consumes the return value of a `@Benchmark` method, and offers `Blackhole` for extra values. |
| Timer cost and resolution | Reads the clock once per batch of invocations, not once per call. |
| Shared state and thread safety | Provides `@State` scopes, so each thread or the whole benchmark gets its own object. |
| Setup cost leaking into timings | Runs `@Setup` and `@TearDown` methods outside the timed region. |
| Statistics | Computes a mean, an error estimate and units, and can print percentiles and raw data. |
| Cross-benchmark interference | Runs benchmarks one after another, each in its own fork. |
How a JMH run is organized
A run has three layers. Understanding them explains most of the output you will see.
- Build time. The annotation processor reads your annotations and writes Java source into
target/generated-sources/annotations. These generated classes contain the timed loops, the state-object wiring, and the code that reads the clock. When something behaves oddly, read these files. They are plain Java. - Launcher. The JVM you start with
java -jar target/benchmarks.jardoes not run your benchmark. It parses options, picks which benchmarks match, and starts child JVMs. - Forks. Each forked JVM runs warmup iterations and then measurement iterations for one benchmark. It sends the numbers back to the launcher over a socket. The launcher merges them across forks.
Forking matters more than it looks. The JIT compiler learns from the program's history. If benchmark A has already run in a JVM, the profile data the JIT collected for shared code, such as an interface call site, may change how benchmark B is compiled. A fresh JVM per benchmark removes that coupling.
A minimal benchmark
The smallest useful benchmark is a class with one annotated method. This one compares nothing yet, it only shows the shape.
package org.sample;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MinimalBenchmark {
private String text = "benchmark";
@Benchmark
public int length() {
return text.length();
}
}You never write a loop, a timer call, or a main method. JMH supplies them. Three details are worth noticing:
- The input comes from a field, not a literal. This keeps the JIT from computing the answer at compile time. A later chapter covers this in detail.
- The method returns its result. JMH passes the returned value to an internal consumer, so the call cannot be removed as dead code.
- The annotations on the class set defaults for every benchmark in it. A command-line option can override each of them.
What JMH does not do
JMH removes measurement artifacts. It cannot tell whether you are measuring the right thing.
- It does not stop constant folding or dead code you write yourself. If you pass a compile-time constant to the code under test, or ignore a second result inside the method, the JIT may still skip the work. You apply the fixes with state fields, return values, and
Blackhole. - It does not make results portable. A score belongs to one JVM version, one set of JVM flags, one CPU and one operating system state. Compare results only from the same setup.
- It does not make small differences meaningful. Always compare the error estimate with the gap between two scores. If the ranges overlap, you have not shown a difference.
- It does not model your application. A microbenchmark has hot caches, a stable branch history, and no other load. A method that wins here can lose in production.
- It does not replace profiling. JMH answers "which of these two is faster in isolation". A profiler answers "where does the time go in the real system".
The most common error at this stage is treating a printed number as truth. JMH gives a well-formed measurement of the code you wrote. If that code did less work than you intended, the number is precise but wrong.
Running it once
Create the project with the Maven archetype, build it, and run it. The next chapter walks through the setup in detail.
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.jarThe first lines of output are a header that lists the JMH version, the JDK, the warmup and measurement settings, the number of forks, and the benchmark mode. Read it every time. It states exactly what was measured, and defaults vary between JMH versions.
Summary of the working model
You write the operation, and JMH generates the loop, controls JVM state, and does the statistics. You remain responsible for the work being real. A good habit is to ask two questions of every benchmark you write. First, could the JIT prove the result without doing the work? Second, is any time that I do not want to measure inside the timed method?
Exercise
A benchmark method calls Math.sqrt(x) on a field and ignores the result, then reports a score of 0.3 ns per operation. Which JMH feature protects against this, and what would you change?
Show answer
JMH does not protect a method that discards its own result. The JIT can remove the call as dead code, so the score reflects an empty method. Change the method to return the value, or pass it to a Blackhole parameter with bh.consume(...). JMH then consumes the value, and the square root has to be computed.
Exercise
Why does JMH run each benchmark in a freshly forked JVM instead of running all benchmarks in the launcher JVM?
Show answer
The JIT compiler profiles code as it runs. Earlier benchmarks can leave profile data, such as the types seen at a shared call site, that changes how later benchmarks are compiled. A new JVM per benchmark gives each one a clean starting state. Multiple forks also average out run-to-run differences in JIT decisions.