Sub topic 7
Sharing data with @State
This chapter assumes you can build and run a JMH project (see "Creating a JMH project") and that you have written a basic @Benchmark method. It covers what @State is, how its three scopes differ, how state objects reach benchmark methods, and the mistakes that cause build errors or wrong numbers.
Why benchmarks need state objects
A benchmark usually needs input data: an array to sum, a map to query, a string to parse. Creating that data inside the @Benchmark method would put the setup cost into every measurement. Hard-coding it as a constant invites the JIT compiler to precompute the answer.
JMH solves both problems with state objects. A state object is an ordinary Java class that holds the benchmark's inputs. JMH creates it, keeps it alive for the measurement, and passes it to your benchmark methods. Because JMH owns the instance's lifetime, the cost of building it stays outside the timed region.
You mark a class as a state object with @State and a scope:
@State(Scope.Benchmark)
public class SharedData { ... }The three scopes
The scope decides how many instances of the state class exist and which threads see which instance.
| Scope | Instances | Visible to | Typical use |
|---|---|---|---|
| `Scope.Thread` | One per benchmark thread | Only the thread that owns it | Per-thread cursors, counters, scratch buffers |
| `Scope.Benchmark` | One for the whole benchmark | All threads | Read-only shared input such as a lookup table |
| `Scope.Group` | One per thread group | Threads in the same `@Group` | Producer/consumer benchmarks |
With a single benchmark thread (the default), Thread and Benchmark behave the same, because there is only one thread. The difference appears when you run with @Threads or -t and more than one thread.
Scope.Group only matters when you split threads into groups with @Group and @GroupThreads. This chapter does not use it again.
Two ways to declare state
The benchmark class as its own state
The simplest option is to annotate the benchmark class itself. Its fields become the state, and @Benchmark methods use them directly. The SumBenchmark class from the earlier chapter does this with @State(Scope.Benchmark).
Separate state classes passed as parameters
For more control, declare dedicated state classes and list them as parameters of the benchmark method. JMH finds the parameter type, sees the @State annotation, and injects the right instance.
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.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
public class StateScopeBenchmark {
@State(Scope.Benchmark)
public static class SharedData {
public final int[] values = new int[1_000];
public SharedData() {
for (int i = 0; i < values.length; i++) {
values[i] = i * 3;
}
}
}
@State(Scope.Thread)
public static class Cursor {
public int index;
}
@Benchmark
public int readNext(SharedData shared, Cursor cursor) {
int value = shared.values[cursor.index];
cursor.index = (cursor.index + 1) % shared.values.length;
return value;
}
}SharedData is read-only after construction, so it is safe to share across threads. Cursor is mutable, so each thread gets its own. Separating the two lets you pick the right scope for each piece of data. It also lets several benchmark classes reuse the same state class.
The method returns value so the JIT cannot discard the work. That rule is covered in the dead-code chapter.
Rules for state classes
JMH generates code that instantiates your state classes, so it imposes structural rules. Breaking them usually produces an error during mvn clean verify, not at run time.
- The class must be
public. - A nested state class must be
static. - The class must have a public no-argument constructor. The implicit default constructor qualifies.
- State objects that reference each other must not form a cycle through their scopes in a way that JMH cannot resolve.
A typical error looks like "The instantiated @State annotation only supports public classes" or a complaint about a missing zero-argument constructor. The fix is almost always one of the rules above.
When state is created and how long it lives
JMH creates state objects lazily, when a thread first needs them, and reuses the same instance for every invocation in the measurement. Each fork starts a new JVM, so each fork gets fresh state. By default, @Setup methods run once per trial, which is one fork's full run of warmup plus measurement. The next chapter covers @Setup and @TearDown.
Two consequences follow:
- Anything your benchmark changes in state persists between invocations. If a benchmark appends to a list held in state, the list grows throughout the run, and later invocations measure a different list than earlier ones. Either keep the benchmark free of lasting changes, or reset the state with a setup at the
Invocationlevel. - A
Scope.Threadinstance is created once per thread, not once per call. TheCursorabove keeps its index across all invocations on that thread, which is what you want here.
Thread safety with Scope.Benchmark
JMH does not synchronize access to a shared state object. If several threads write to a Scope.Benchmark field, you get a data race and your benchmark is measuring contention, not the operation you meant to test.
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
@State(Scope.Benchmark)
@Threads(4)
public class RacyCounterBenchmark {
private long counter;
@Benchmark
public long increment() {
return ++counter; // unsynchronized write shared by four threads
}
}This benchmark does measure something, but the number reflects cache-line contention and lost updates. Change the scope to Scope.Thread and each thread increments a private counter. Choose Scope.Benchmark only when sharing is the point of the test, or when the shared data is not modified.
State fields help against constant folding
Reading inputs from non-final state fields also protects you from constant folding. The compiler cannot treat a value as a compile-time constant when it comes from a field that might change. The FoldingBenchmark in the dead-code chapter uses a Scope.Thread field x for this reason. Declaring such a field final, or using a static final constant, weakens that protection, so keep benchmark inputs non-final unless you are testing exactly that case.
Common mistakes
- Building inputs inside the
@Benchmarkmethod. The timing then includes construction. Move it into the state constructor or a@Setupmethod. - Using
Scope.Benchmarkfor mutable data under@Threads. Results reflect races, not the operation. - Sharing one big mutable state between unrelated benchmarks. Methods in the same class that use the same state instance can change each other's inputs. Use separate state classes, or keep the state read-only.
- Forgetting
public,static, or the no-argument constructor. The build fails or JMH reports that it cannot instantiate the class.
Exercise
A benchmark class has a nested class Buffer annotated @State(Scope.Benchmark) that holds a byte[] which each benchmark call overwrites. The benchmark runs with @Threads(4). Name two problems with this design and say how you would fix each one.
Show answer
First, the buffer is shared by all four threads and is written without synchronization, so the threads race and the result measures contention, not the operation. Changing the scope to Scope.Thread gives each thread its own buffer. Second, if Buffer is declared as a non-static nested class, or lacks a public no-argument constructor, JMH cannot instantiate it and the build fails. Declare it public static with a public no-argument constructor.