Sub topic 8
Preparing data with @Setup and @TearDown
This chapter assumes you can write a basic @Benchmark method, you know what @State and its scopes do, and you can build and run a JMH jar with Maven. Here you will learn how @Setup and @TearDown control when data is created and released, and what each level costs the measurement.
Why setup code belongs outside the benchmark method
A benchmark method is called millions of times. Anything inside it is part of the score. If a method builds a 10,000-element array and then sums it, the score measures both the allocation and the sum. You cannot tell them apart afterward.
JMH solves this with lifecycle annotations on methods of a @State class:
@Setupmarks a method that JMH runs before the benchmark code that uses the state.@TearDownmarks a method that JMH runs after that code has finished.
JMH does not include the time spent in these methods in the score. The annotated methods can be public or non-public, but they must be instance methods of the state class, take no arguments, and return nothing.
The three levels
Both annotations take a Level value. The level decides how often the method runs.
| Level | Runs | Typical use |
|---|---|---|
| `Level.Trial` (default) | Once per fork, around all warmup and measurement iterations | Build large read-only data, open files or connections |
| `Level.Iteration` | Before and after every warmup or measurement iteration | Reset data that an iteration mutates, clear caches |
| `Level.Invocation` | Before and after every single benchmark call | Restore state that each call destroys |
A trial is one complete run of a benchmark inside one forked JVM. With @Fork(2) there are two trials, so a Level.Trial setup runs twice for each parameter combination.
Level.Trial: build once, read many times
Most benchmarks read their input and do not change it. For these, Level.Trial is the right choice because the cost is paid once and the data stays the same for every iteration.
package org.sample;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class BinarySearchBenchmark {
@Param({"1000", "100000"})
public int size;
private int[] sorted;
private int target;
@Setup(Level.Trial)
public void prepare() {
Random random = new Random(42);
sorted = new int[size];
for (int i = 0; i < size; i++) {
sorted[i] = random.nextInt();
}
Arrays.sort(sorted);
target = sorted[size / 2];
}
@TearDown(Level.Trial)
public void release() {
sorted = null;
}
@Benchmark
public int search() {
return Arrays.binarySearch(sorted, target);
}
}The fixed seed 42 makes the data identical in every fork, so differences between runs come from the machine and not from the input. @Param values are injected before @Setup runs, so size is already set when prepare() executes.
Level.Iteration: reset between iterations
Some benchmarks change their data. A benchmark that adds to a list makes the list longer on each call. Without a reset, later iterations work on a bigger list than earlier ones, and the average mixes different workloads.
Level.Iteration rebuilds the data at each iteration boundary:
package org.sample;
import java.util.ArrayList;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@State(Scope.Thread)
public class ListGrowthBenchmark {
private List<Integer> list;
@Setup(Level.Iteration)
public void newList() {
list = new ArrayList<>();
}
@Benchmark
public boolean add() {
return list.add(1);
}
}Each iteration still makes many calls, so the list grows within an iteration. This is acceptable only if one iteration is short enough that the growth does not change the cost per call. Check this by comparing iteration scores in the output. If the numbers drift upward within the run, the benchmark is measuring growth and not the cost of a single add.
Level.Invocation: use it rarely
Level.Invocation runs the method around every call. It looks like the exact fix for destructive benchmarks, such as sorting an array in place, because each call needs fresh unsorted data. It has real costs, and the JMH documentation warns against it for fast benchmarks.
- JMH must time each call individually and cannot time a whole batch. The timer call itself costs roughly tens of nanoseconds.
- Setup and teardown run between calls, which disturbs CPU caches and branch predictors in ways that real code would not experience.
- With multiple threads, JMH must synchronize around the setup, which adds contention.
Use it only when a single call takes much longer than the timer overhead, for example more than a few microseconds, and only when a cheaper alternative does not exist.
package org.sample;
import java.util.Arrays;
import java.util.Random;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@State(Scope.Thread)
public class SortBenchmark {
private static final int SIZE = 100_000;
private final int[] original = new Random(1).ints(SIZE).toArray();
private int[] work;
@Setup(Level.Invocation)
public void copy() {
work = original.clone();
}
@Benchmark
public int[] sort() {
Arrays.sort(work);
return work;
}
}Sorting 100,000 integers takes milliseconds, so the per-invocation timer overhead is negligible here. Sorting 10 integers would take nanoseconds, and this approach would produce misleading results. For tiny operations, put the clone inside the benchmark method and accept that you are measuring clone plus sort, or change the design so the operation does not destroy its input.
@TearDown: releasing resources
@TearDown mirrors @Setup. Use it for anything that holds resources outside the Java heap or outlives the trial: open files, sockets, thread pools, temporary directories.
package org.sample;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
@State(Scope.Benchmark)
public class FileReadBenchmark {
private Path file;
@Setup(Level.Trial)
public void create() throws IOException {
file = Files.createTempFile("jmh", ".txt");
Files.writeString(file, "hello\n".repeat(1000));
}
@TearDown(Level.Trial)
public void delete() throws IOException {
Files.deleteIfExists(file);
}
@Benchmark
public long readSize() throws IOException {
return Files.readString(file).length();
}
}This example uses Files.writeString and String.repeat, which need Java 11 or later. Setup and teardown methods may declare checked exceptions. If a setup method throws, JMH reports the benchmark as failed instead of recording a score.
Setup rules that cause common errors
- Scope decides who runs the method. With
Scope.Thread, each benchmark thread has its own state object and runs its own setup. WithScope.Benchmark, one shared object exists and setup runs once, not once per thread. - Setup runs per state object, not per benchmark. If two benchmark methods in the same class share a
@State(Scope.Benchmark)class, they run in separate trials by default, so each gets its own setup. A benchmark that takes two state classes as parameters triggers setup in both. - Level.Trial is not once per JVM run of your program. It is once per fork per parameter combination. Expect it to run as many times as
forks × parameter combinations. - Do not do setup lazily inside
@Benchmark. A pattern likeif (data == null) data = build();puts a branch in every call and lets the first call pay the cost, which pollutes the first iteration. - Final fields set in the constructor are not a replacement. They work, as in
SortBenchmarkabove, but they run when JMH constructs the state object. A@Paramvalue is not yet available there, so anything depending on a parameter needs@Setup.
Choosing a level
- Does the benchmark leave the data unchanged? Use
Level.Trial. - Does it change the data, but a run of many calls stays representative? Use
Level.Iteration. - Does each call destroy its input, and does a call take far longer than a timer reading? Use
Level.Invocation. - Is the call too fast for that? Restructure the benchmark so it does not destroy its input.
Exercise
A benchmark pops elements from a stack that holds 1,000,000 elements, and each call takes about 20 ns. A colleague proposes rebuilding the stack in a @Setup(Level.Invocation) method so it never runs empty. Why is this a poor choice, and which level would you use instead?
Show answer
At 20 ns per call, the per-invocation timing overhead and the cache disturbance from rebuilding a million-element stack would dominate the score, and the rebuild would be far more expensive than the call itself. Use @Setup(Level.Iteration) to refill the stack, and keep each iteration short enough that it cannot empty the stack. Alternatively, pair each pop with a push inside the benchmark method so the size stays constant, and state this in the benchmark's description.
Exercise
You run a benchmark with @Fork(3) and two @Param values for size. Its @Setup(Level.Trial) method prints a line. How many lines appear, and why?
Show answer
Six lines. A trial runs once per fork for each parameter combination, so 3 forks times 2 parameter values gives 6 trials, and the trial setup runs once in each.