Sub topic 8
Preparing data with @Setup and @TearDown
This chapter assumes you can write a basic @Benchmark method and know what @State does. You should also know that JMH runs warmup and measurement iterations inside forked JVMs.
Why setup code lives outside the benchmark
Anything inside a @Benchmark method is timed. Building a 10,000-element array there would measure the array construction and the work you care about together. JMH lets you move preparation into methods on a @State class. These methods run outside the measured region.
You mark them with two annotations:
@Setupruns before the benchmark code that needs the state.@TearDownruns afterward, to release resources such as files, threads, or connections.
The three levels
Both annotations take a Level argument that controls how often the method runs.
| Level | Runs | Typical use |
|---|---|---|
| `Level.Trial` (default) | Once per fork, around all iterations | Build large read-only data, open resources |
| `Level.Iteration` | Before and after each warmup or measurement iteration | Reset state that drifts during an iteration |
| `Level.Invocation` | Before and after every benchmark call | Restore state that each call destroys |
Example: a benchmark that destroys its input
Sorting an array in place changes it. If you sort the same array on every call, only the first call sorts unsorted data. The rest sort already-sorted data. The input has to be restored before each call.
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.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Thread)
public class SortBenchmark {
private int[] source;
private int[] work;
@Setup(Level.Trial)
public void createSource() {
Random random = new Random(42);
source = new int[50_000];
for (int i = 0; i < source.length; i++) {
source[i] = random.nextInt();
}
}
@Setup(Level.Invocation)
public void copySource() {
work = source.clone();
}
@Benchmark
public int[] sort() {
Arrays.sort(work);
return work;
}
}The random data is built once per trial with a fixed seed, so every fork sorts the same values. A fresh copy is made before every call. JMH does not include the copy in the score.
Releasing resources with @TearDown
A @TearDown method uses the same level argument. It runs at the matching point on the way out.
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.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
@State(Scope.Benchmark)
public class FileBenchmark {
private Path file;
@Setup
public void createFile() throws IOException {
file = Files.createTempFile("jmh", ".txt");
Files.writeString(file, "hello jmh");
}
@TearDown
public void deleteFile() throws IOException {
Files.deleteIfExists(file);
}
@Benchmark
public int readFile() throws IOException {
return Files.readString(file).length();
}
}Files.writeString and Files.readString need Java 11, which this tutorial targets. Because the state is Scope.Benchmark, one file is shared by all threads. JMH calls the setup and teardown once, not once per thread.
Common mistakes
- Setup runs per state instance. With
Scope.Thread, each thread runs its own setup, which matters for expensive setup. - Fields that setup assigns must not be
final, or the JIT may treat them as constants and fold the work away. - Do not rely on setup timing. If setup is slow, it only slows the run and does not change the score.
Exercise
A benchmark calls Collections.shuffle(list) on a shared list. Which setup level would you pick to keep the input equivalent on every call, and what is the main drawback?
Show answer
Use @Setup(Level.Invocation) to rebuild or copy the list before each call. The drawback is timing overhead around every invocation, which makes results unreliable for very short benchmarks. Shuffling an already-shuffled list is equivalent input, so Level.Iteration or Level.Trial would also work and avoids the overhead.