Sub topic 4
Creating a JMH project
This chapter shows how to create a JMH project, what the build produces, and why the build is arranged that way. It assumes you can read a Maven pom.xml, run mvn from a terminal, and use Java annotations. You should also know that the JVM compiles hot code while the program runs. You will use JDK 11 or later and Maven 3.6 or later.
What a JMH project must do
A JMH benchmark is a normal Java class with annotations. Two things make the build different from an ordinary library:
- Code generation at compile time. JMH ships an annotation processor,
jmh-generator-annprocess. Whenjavacruns, the processor reads your@Benchmarkmethods and writes extra classes that wrap each one in a measurement loop. It also writes a registry file,META-INF/BenchmarkList, which lists every benchmark it found. - A self-contained jar. JMH starts a fresh JVM (a fork) for each benchmark run. That child JVM needs
jmh-coreand your classes on its classpath. The simplest way to guarantee this is to package everything into one executable jar.
The generated wrapper code is the reason you should not call @Benchmark methods yourself or run the class like a unit test. The wrapper holds the timing loop, the state handling and the result consumption.
Option 1: generate a project from the archetype
The archetype is the quickest route and the one the JMH authors recommend. Run:
mvn archetype:generate \
-DinteractiveMode=false \
-DarchetypeGroupId=org.openjdk.jmh \
-DarchetypeArtifactId=jmh-java-benchmark-archetype \
-DgroupId=org.sample \
-DartifactId=benchmarks \
-Dversion=1.0
cd benchmarks
mvn clean verify
java -jar target/benchmarks.jarThe first command creates a benchmarks directory. mvn clean verify compiles, runs the annotation processor and shades the jar. The last command runs every benchmark in the project.
If you do not pass -DarchetypeVersion, Maven picks the newest archetype release. To make the build reproducible, add -DarchetypeVersion=1.37 (or the release you want) to the first command.
What you get
| Path | Purpose |
|---|---|
| `pom.xml` | Declares `jmh-core`, the annotation processor, the compiler settings and the shade plugin. |
| `src/main/java/org/sample/MyBenchmark.java` | A placeholder class with an empty `@Benchmark` method. Replace it with your own. |
| `target/classes/META-INF/BenchmarkList` | The registry the annotation processor writes. Appears after compiling. |
| `target/benchmarks.jar` | The executable jar. Appears after `mvn verify`. |
| `target/original-benchmarks.jar` | The unshaded jar. You can ignore it. |
Benchmarks live in src/main, not src/test. The annotation processor and the shade plugin work on main classes, and a benchmark is the product of this module, not a test of it.
Expect a long first run
Running the placeholder with no options uses JMH's defaults: 5 forks, each with 5 warmup iterations of 10 seconds and 5 measurement iterations of 10 seconds. That is roughly eight minutes for one benchmark method. For quick checks, override the settings on the command line (covered later in this tutorial) or with annotations such as @Fork, @Warmup and @Measurement. Use the full defaults when you want numbers you will report.
Option 2: add JMH to an existing module
Sometimes you cannot start from the archetype. You can reproduce what it does with a POM. This one is complete and builds a benchmarks.jar for Java 11:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.sample</groupId>
<artifactId>benchmarks</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<jmh.version>1.37</jmh.version>
<maven.compiler.release>11</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh.version}</version>
</dependency>
</dependencies>
<build>
<finalName>benchmarks</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.openjdk.jmh.Main</mainClass>
</transformer>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>Three parts matter:
jmh-coreis the only runtime dependency. Do not useprovidedscope, or the shade plugin will leave it out of the jar.annotationProcessorPathsputs the generator on the processor path, so it does not end up in your runtime classpath. Without it (or an equivalent dependency), nothing writesBenchmarkListand JMH finds no benchmarks.ManifestResourceTransformersetsorg.openjdk.jmh.Mainas the jar's entry point. That is whyjava -jar target/benchmarks.jarworks and accepts JMH's command-line options.
The signature filters matter when a dependency is a signed jar. Merging signed jars into one produces invalid signatures, and the JVM then refuses to load the result with a security error.
Keep benchmarks in their own module
If you want to benchmark code from an existing application, put the benchmarks in a separate Maven module that depends on the application's jar. This keeps the shade plugin, the annotation processor and JMH out of your production artifact. The shaded benchmark jar then contains the application classes as a normal dependency.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Unable to find the resource: /META-INF/BenchmarkList` | Annotation processor did not run | Check `annotationProcessorPaths` or enable annotation processing in the IDE |
| `No matching benchmarks. Miss-spelled regexp?` | The filter given on the command line matches no benchmark | Check the class name. The argument is a regular expression matched against the fully qualified benchmark name |
| `SecurityException: Invalid signature file digest` | Signed jars were merged without the signature filters | Add the `META-INF/*.SF`, `*.DSA` and `*.RSA` excludes |
| `no main manifest attribute` | `ManifestResourceTransformer` is missing | Add it with `org.openjdk.jmh.Main` |
| Old benchmarks still run after edits | Stale `target/` directory | Use `mvn clean verify` |
Checking that the build works
After mvn clean verify, you can list the benchmarks the jar knows about without running them:
java -jar target/benchmarks.jar -lAn empty list means the annotation processor did not run. A list with your methods in it means the project is ready. The -l flag only reads BenchmarkList, so it takes less than a second.
Exercise
You add JMH to a module with jmh-core as a dependency and a @Benchmark method in src/main/java. mvn package succeeds, but java -jar target/benchmarks.jar -l lists no benchmarks. Name the most likely cause and how you would confirm it.
Show answer
The jmh-generator-annprocess annotation processor did not run, so META-INF/BenchmarkList was never generated. Confirm by checking whether target/classes/META-INF/BenchmarkList exists. Fix it by adding jmh-generator-annprocess under annotationProcessorPaths in maven-compiler-plugin, then run mvn clean verify.
Exercise
Why does the archetype produce a shaded jar with org.openjdk.jmh.Main as its main class, and not simply run benchmark classes from target/classes?
Show answer
JMH starts each benchmark in a forked JVM, and that JVM needs jmh-core, the generated classes and your code on its classpath. One self-contained jar gives the same classpath to the launcher and every fork, and its manifest entry point lets java -jar accept JMH's command-line options.