Sub topic 15
Benchmarking with multiple threads
So far each benchmark ran on one thread. Many real workloads do not: counters, caches, queues and locks are used by several threads at once. Their cost depends on contention, which a single-threaded run cannot show. This chapter covers how JMH runs benchmark methods on several threads, how state scope affects the result, and how to read the score. It assumes you can write a @Benchmark method and know the @State scopes from earlier chapters.
Setting the thread count
The @Threads annotation sets how many threads call the benchmark method at the same time. It works on a method or a class. The default is one thread.
package org.sample;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
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.Threads;
import org.openjdk.jmh.annotations.Warmup;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
@Threads(4)
public class CounterBenchmark {
private final AtomicLong atomic = new AtomicLong();
private final LongAdder adder = new LBenchmark
public long atomicIncrement() {
return atomic.incrementAndGet();
}
@Benchmark
public void adderIncrement() {
}
}Both methods increment a counter from four threads. @State(Scope. all four threads share one CounterBenchmark instance, so they all update the same AtomicLong. Every updatees for the same memory location. LongAdder` spreads updates over several internal cells and combines them only when you read the total, so it usually scales better under contention.
Use @Threads(Threads.MAX) to run one thread per available processor. On the command line, -t 4 or -t max overrides the annotation:
java -jar target/benchmarks.jar CounterBenchmark -t maxState scope decides what the threads share
With one thread, the scope of a state object makes little difference. With several threads, it decides whether they contend.
| Scope | Instances created | Effect with several threads |
|---|---|---|
| `Scope.Thread` | One per benchmark thread | No sharing. Threads do not contend on the state. |
| `Scope.Benchmark` | One for all threads | Threads share and contend on the same object. |
| `Scope.Group` | One per thread group | Threads in one group share it. See the group section below. |
Pick the scope that matches the situation you want to measure. If you want to know how a ConcurrentHashMap behaves when threads hit the same map, use Scope.Benchmark. If each thread should work on its own private buffer, use Scope.Thread.
The scope also changes when @Setup runs. A Scope.Thread state is created once for each thread, so its @Setup(Level.Trial) method runs once per thread. A Scope.Benchmark state is created once, so its setup runs once. Do not assume setup runs once if the state is thread-scoped.
Reading a multithreaded score
The meaning of the score depends on the mode.
- Throughput reports the total operations per unit of time summed over all threads. Four threads that each manage 10 ops/ms give a score near 40 ops/ms.
- AverageTime reports the time per operation as a thread experiences it. Adding threads does not divide this number. If contention slows each call, the time per operation goes up.
Because of this, compare results for the same mode only. A throughput score only says something about scaling when you also run the same benchmark with a different thread count.
A scaling run varies the thread count and keeps everything else fixed:
java -jar target/benchmarks.jar CounterBenchmark.atomicIncrement -t 1
java -jar target/benchmarks.jar CounterBenchmark.atomicIncrement -t 2
java -jar target/benchmarks.jar CounterBenchmark.atomicIncrement -t 4With good scaling, throughput grows roughly in proportion to the thread count. With a contended AtomicLong, throughput often stays flat or even drops as threads are added. That drop is the result you were looking for, not noise.
Asymmetric workloads with groups
Sometimes threads should do different jobs, for example one writer and several readers. A group lets you run several @Benchmark methods together, each on its own number of threads. Mark the methods with @Group and give each a thread count with @GroupThreads.
package org.sample;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
public class ReadWriteBenchmark {
private static final int KEYS = 1024;
@State(Scope.Group)
public static class Shared {
final ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
@Setup(Level.Trial)
public void fill() {
for (int i = 0; i < KEYS; i++) {
map.put(i, i);
}
}
}
@Benchmark
@Group("mixed")
@GroupThreads(1)
public Integer write(Shared shared) {
int key = ThreadLocalRandom.current().nextInt(KEYS);
return shared.map.put(key, key + 1);
}
@Benchmark
@Group("mixed")
@GroupThreads(3)
public Integer read(Shared shared) {
return shared.map.get(ThreadLocalRandom.current().nextInt(KEYS));
}
}All four threads in the mixed group share one Shared instance, because its scope is Scope.Group. One thread runs write while three run read. JMH reports a result for the group as a whole and a secondary result for each method, such as ReadWriteBenchmark.mixed:read. The key range is fixed, so the map does not grow during the run. A benchmark that adds new entries on every call would change its own working set as it runs and distort later iterations.
Do not combine @Threads with @Group. The group's thread total comes from the sum of the @GroupThreads values (here 1 + 3 = 4). If you want more threads, JMH runs several copies of the whole group, so -t 8 gives two copies of this four-thread group.
Pitfalls
- More threads than cores. If the thread count exceeds the number of hardware threads, the operating system time-slices them. The score then reflects scheduler behavior as well as your code. Keep the count at or below the processor count unless oversubscription is the point of the test.
- Hidden sharing. Static fields, a shared
Random, or a shared output list make threads contend even when the state isScope.Thread. UseThreadLocalRandominstead of one sharedRandom. - Other load on the machine. A busy laptop or a build running in the background distorts multithreaded runs far more than single-threaded ones. Close other work and run on a quiet host.
- Dead code in every thread. Each thread still needs its result returned or passed to a
Blackhole. JMH gives each thread its ownBlackhole, so you can take it as a method parameter just as before.
Exercises
Exercise
A benchmark runs @Threads(4) in Mode.Throughput and reports 80 ops/ms. The same method with @Threads(1) reports 60 ops/ms. What does this tell you about scaling, and what would you expect from ideal scaling?
Show answer
The score is the total across all threads, so four threads gave only about 1.3 times the single-thread throughput (80 / 60). Ideal scaling would give about 240 ops/ms (4 x 60). The result points to heavy contention on shared state or a limit on the available cores, so you should check the state scope and whether the machine has four free hardware threads.
Exercise
You change the state of a benchmark from Scope.Benchmark to Scope.Thread and the throughput at 8 threads rises sharply. What does this show, and what must you check before drawing a conclusion about your real application?
Show answer
It shows that sharing one object between threads caused contention, because with Scope.Thread each thread works on its own instance. Before concluding anything about the real application, check whether the application also shares the object between threads. If it does, the Scope.Thread result is unrealistic, because removing the sharing removed the behavior you wanted to measure.