lf215 lf215 - 2 months ago 19
Java Question

jmh: Run benchmark concurrently

I'm running a jmh benchmark, but the invocations in each trial are occurring in serial. How can I make the invocations run concurrently?

Here's a summary of my code:


@State(Scope.Benchmark)
public class FooBenchmark {
@Param({"123456"})
public int barId;

@Setup
public void setup() {
}

@Benchmark
public void run(Blackhole hole) {
System.out.println("A"); // for proof that it's serial (see below)
...
System.out.println("B"); // for proof that it's serial (see below)
}
}


This will print A and then B. Will never give two consecutive A's or B's.

Answer

If you want to explicitly define the total amount of threads to use during your test, you need to annotate your test method (method annotated with @Benchmark) with @Threads(numberOfThreads) as next:

@Threads(10)
@Benchmark
public void run(Blackhole hole) {

In this example, 10 threads will execute the test method concurrently.

As reminder, here is part of the doc that describes this annotation:

@Threads: Number of threads to use for the test. The default is Runtime.getRuntime().availableProcessors().