Java Core & JVM (50 Qs)•Part 3: JVM Internals, Low-Latency Systems & Production Tuning (25 - 35)
How do you write reliable micro-benchmarks in Java using JMH (Java Microbenchmark Harness)?
senior LevelCode ExampleTesting
In Simple Words:
Never benchmark Java code with System.currentTimeMillis() in a simple for loop! The JIT compiler optimizes away unused code (Dead Code Elimination), inlines methods dynamically, and distorts results during initial cold interpretation. JMH is the official OpenJDK toolchain for measuring nano-second and micro-second execution times accurately.
JMH Safeguards:
- Warmup Iterations: Exercises the code to ensure C2 JIT compilation reaches steady state.
Blackhole: Consumes computation results to prevent the JIT from eliminating "dead code".- Forking: Spawns clean JVM processes to avoid profile pollution from previous runs.
java
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Thread)
@Fork(2)
@Warmup(iterations = 3)
public class StringBenchmark {
@Benchmark
public void testStringConcat(Blackhole bh) {
String s = "Hello" + " " + "World";
bh.consume(s); // Prevents compiler dead-code elimination!
}
}