---
name: benchmark-java
description: Write Java benchmarks using JMH (Java Microbenchmark Harness). Use when: user wants to benchmark Java code, measure JVM performance, optimize Java programs, or compare implementations using JMH's statistical analysis.
license: MIT
---
# Java Benchmarking
This skill covers benchmarking Java code using JMH (Java Microbenchmark
Harness), the standard for Java performance measurement.
## Setup
### Maven
```xml
org.openjdk.jmh
jmh-core
1.37
org.openjdk.jmh
jmh-generator-annprocess
1.37
```
```xml
org.apache.maven.plugins
maven-shade-plugin
3.5.1
package
shade
benchmarks
org.openjdk.jmh.Main
```
### Gradle
```groovy
plugins {
id 'java'
id 'me.champeau.jmh' version '0.7.1'
}
jmh {
fork = 2
warmupIterations = 10
iterations = 10
warmupTime = '1s'
measurementTime = '1s'
}
```
## Writing Benchmarks
### Basic Benchmark
```java
import org.openjdk.jmh.annotations.*;
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class MyBenchmark {
@Benchmark
public int fibonacci() {
return fib(20);
}
private int fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
}
```
### Benchmark Modes
| Mode | Description | Use Case |
| ---------------- | ------------------------ | ------------------------- |
| `Throughput` | Operations per time | Default, batch processing |
| `AverageTime` | Time per operation | Latency |
| `SampleTime` | Sample random operations | Variable latency |
| `SingleShotTime` | Single operation time | Cold start |
### State Management
```java
@State(Scope.Thread) // Each thread gets own instance
@State(Scope.Benchmark) // Shared across all threads
@State(Scope.Group) // Shared within group
public class MyBenchmark {
@Setup(Level.Iteration) // Before each iteration
@TearDown(Level.Iteration) // After each iteration
public void setup() {
data = new int[1000];
// Initialize
}
@Benchmark
public void benchmark() {
// Use data
}
}
```
### Parameters
```java
@Param({"10", "100", "1000"})
private int size;
@Benchmark
public void benchmark() {
// size is set to each value
for (int i = 0; i < size; i++) { ... }
}
```
### Preventing DCE with Blackhole
```java
import org.openjdk.jmh.infra.Blackhole;
@Benchmark
public void benchmark(Blackhole blackhole) {
int result = compute();
blackhole.consume(result); // Prevents DCE
}
// Or: JMH automatically blackholes return values
@Benchmark
public int benchmark() {
return compute(); // Auto-consumed
}
```
### Multiple Benchmarks in Class
```java
public class FibonacciBenchmark {
@Benchmark
public int recursive() { return fib(20); }
@Benchmark
public int iterative() {
int a = 0, b = 1;
for (int i = 0; i < 20; i++) {
int temp = a;
a = b;
b = temp + b;
}
return a;
}
}
```
## Running Benchmarks
### Maven
```bash
mvn jmh:jmh
mvn package -DskipTests
java -jar target/benchmarks.jar
```
### Common Options
| Option | Description |
| ---------------- | ------------------------------ |
| `-f 3` | Fork 3 JVM instances |
| `-wi 10` | 10 warmup iterations |
| `-i 10` | 10 measurement iterations |
| `-w 1s` | 1 second warmup time |
| `-r 1s` | 1 second measurement time |
| `-rf json` | Output format: json, csv, text |
| `-o results.txt` | Output file |
### Examples
```bash
# Run all
java -jar target/benchmarks.jar
# Specific benchmark
java -jar target/benchmarks.jar FibonacciBenchmark.recursive
# Fork settings
java -jar target/benchmarks.jar -f 3 -wi 10 -i 10
# JSON output
java -jar target/benchmarks.jar -rf json -o results.json
# List available
java -jar target/benchmarks.jar -l
```
### Output
```
Benchmark Mode Cnt Score Error Units
FibonacciBenchmark.recursive thrpt 10 123.456 ops/ms
FibonacciBenchmark.iterative thrpt 10 456.789 ops/ms
```
## Configuration Annotations
```java
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Fork(value = 2, warmup = 1) // 2 forks, 1 warmup fork
@Threads(4) // Use 4 threads, or Threads.MAX
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class MyBenchmark { ... }
```
## Profiling Java
### async-profiler (Recommended)
```bash
# Install
wget https://github.com/async-profiler/async-profiler/releases/latest/download/async-profiler-linux-x64.tar.gz
# CPU profile
./profiler.sh -d 30 -f cpu.html
# Memory allocation
./profiler.sh -d 30 -e alloc -f alloc.html
# Lock contention
./profiler.sh -d 30 -e lock -f lock.html
```
### Java Flight Recorder (JFR)
```bash
# Start recording
java -XX:StartFlightRecording:filename=recording.jfr,duration=60s -jar benchmarks.jar
# Or attach to running process
jcmd JFR.start settings=profile filename=recording.jfr
# View
jmc -open recording.jfr
```
### VisualVM
```bash
jvisualvm
# Connect to PID, CPU/Memory tabs for profiling
```
### jstack (Threads)
```bash
jstack
jstack -l # With locks
```
### jmap (Memory)
```bash
jmap -heap # Heap summary
jmap -histo # Object histogram
jmap -dump:file=heap.hprof # Heap dump
```
## Common Pitfalls
1. **Forking** - JMH forks to avoid state carryover; don't disable unless you
understand the risks
2. **Warmup** - JMH defaults may be too short; verify steady state
3. **Blackhole** - Always consume results or return them
4. **Boxing** - Use primitives (`int[]`, not `Integer[]`) to avoid autoboxing
5. **State sharing** - Understand Thread vs Benchmark scope implications
6. **Dead code** - What you don't use gets eliminated
## Quick Reference
| Task | Command |
| -------------- | ---------------------------------------- |
| Run benchmarks | `java -jar target/benchmarks.jar` |
| Warmup/forks | `java -jar ... -f 3 -wi 10` |
| JSON output | `java -jar ... -rf json -o results.json` |
| CPU profile | `./profiler.sh -d 30 -f cpu.html ` |
| JFR recording | `jcmd JFR.start filename=jfr.jfr` |
| Thread dump | `jstack ` |
| Heap dump | `jmap -dump:file=heap.hprof ` |
---
## Related Skills
- **java**: Best practices for writing robust Java avoiding null traps, equality
bugs, and concurrency pitfalls