Sub topic 10
Dead-code elimination and Blackhole
This chapter assumes you can write a basic @Benchmark method and have a working JMH project from the earlier chapters. You should also know that the JIT compiler optimizes hot code at runtime.
The problem: work that nobody uses
The JIT compiler may remove any computation whose result is never used, as long as removing it cannot change what the program observably does. This is dead-code elimination (DCE). In production code it is a useful optimization. In a benchmark it can make the measured code vanish.
Here is a benchmark that looks reasonable but measures almost nothing:
@Benchmark
public void deadCode() {
Math.log(x); // result unused, the JIT may remove the call
}Math.log has no side effects. Nothing reads its result, so the compiled version of deadCode can be an empty method. The benchmark then reports a score of about 0.3 to 1 ns per operation, which is the cost of JMH's own loop, not of the logarithm.
DCE is hard to catch because nothing fails. The benchmark runs, prints a number, and the number looks plausible. A score that is suspiciously small, or that does not change when you change the input, is a hint that the work was removed.
How the JIT decides what is dead
The compiler tracks where each value flows. If a value never reaches a field write, a return value, a call it cannot see through, or another observable effect, the computation that produced it can be dropped. Common triggers in benchmarks:
- A local variable that is assigned but never read.
- A method call whose return value is ignored and whose body the JIT can inline and prove side-effect free.
- A loop whose results are overwritten on every iteration, so only the last one is needed.
Fix 1: return the result
The simplest fix is to return the value. JMH generates code around your method that takes the returned value and passes it to a Blackhole, an object whose job is to make a value look used to the JIT.
@Benchmark
public double returned() {
return Math.log(x); // JMH consumes the returned value
}Prefer this form when the benchmark produces one result. It has no extra code in your method, and the consumption cost is small and the same for every benchmark.
Fix 2: pass results to a Blackhole
A method can return only one value. If a benchmark produces several results that all need to stay alive, ask JMH for a Blackhole by adding it as a parameter. JMH injects it, and you call consume on each result:
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Thread)
public class TwoResultsBenchmark {
private double x = Math.PI;
@Benchmark
public void logAndSqrt(Blackhole bh) {
bh.consume(Math.log(x));
bh.consume(Math.sqrt(x));
}
}consume has overloads for all primitive types and for Object, so the values are not boxed. The method can then return void.
You could instead combine the results into one value, for example return Math.log(x) + Math.sqrt(x);. That works, but it adds an addition to the measured work. Using a Blackhole keeps the measured operations separate.
Why a Blackhole works
A Blackhole hides a decision from the compiler. Conceptually, consume compares the value against a field that the JIT cannot prove will never match, and it only writes something in that unlikely case. The JIT must keep the value alive to perform the comparison, but in practice the write never happens, so the cost stays low.
Newer JMH versions running on recent JDKs can use compiler support for this instead, so consume costs even less. You do not need to know which mechanism applies to write correct benchmarks. You only need the rule: every result you care about must reach a return statement or a Blackhole.
Loops and the "last value" trap
DCE can hide inside loops. Consider a benchmark that tries to measure repeated logarithms:
package org.sample;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
@State(Scope.Thread)
public class LoopBenchmark {
private double x = Math.PI;
@Benchmark
public double lastOnly() {
double result = 0;
for (int i = 0; i < 100; i++) {
result = Math.log(x + i); // earlier iterations are overwritten
}
return result;
}
@Benchmark
public void everyValue(Blackhole bh) {
for (int i = 0; i < 100; i++) {
bh.consume(Math.log(x + i));
}
}
}In lastOnly, only the final value is returned. The JIT can see that the 99 earlier results are overwritten and may skip them. everyValue consumes each result, so all 100 calls stay.
Note that a manual loop inside a @Benchmark method has its own problems. JMH already loops over your method, and the JIT can unroll or vectorize your inner loop in ways that differ from real use. Prefer one operation per invocation and let JMH repeat it. Use an inner loop only when you want to measure the loop itself, such as the sum benchmark over an array in the earlier chapters.
What a Blackhole does not do
Keep these limits in mind:
- It does not stop constant folding. If the input is a constant, such as
Math.log(Math.PI), the JIT can compute the answer at compile time and the benchmark measures only the consumption. Read inputs from@Statefields instead. The next chapter covers this. - It does not make the measured code representative. It only keeps the code alive.
- It is not free. Each
consumecall adds a small, fixed cost. Calling it hundreds of times per invocation can make that cost visible in the score. Blackhole.consumeCPU(tokens)is a different tool. It burns a controlled amount of CPU time and is used to simulate work, not to keep results alive.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `void` benchmark that ignores a pure result | Work may be removed, score near zero | Return the value or consume it |
| Returning only one of several results | The others may be removed | Use `Blackhole` for each result |
| Storing results in a local variable only | Local is dead, work may be removed | Return it or consume it |
| Keeping the result but ignoring a helper's side-effect-free computation | Helper may be removed | Consume the helper's output too |
| Consuming inside a tight loop for a cheap operation | Consume cost dominates | Measure one operation per call |
Checking your benchmark
You cannot see DCE directly in the output, so check indirectly:
- Compare against an empty benchmark. Add
@Benchmark public void baseline() {}. If your benchmark scores about the same as the baseline, it is probably measuring nothing. - Change the input size with
@Param. A score that does not grow with the input is a warning sign. - Run with the GC profiler (
-prof gc). A benchmark that should allocate but reports zero allocation may have had that work removed.
Exercise
A benchmark method is declared public void parse() { Integer.parseInt(text); }, where text is a field in a @State object. It reports 0.4 ns/op, which is far lower than expected. Why, and give two different ways to fix it.
Show answer
Integer.parseInt has no side effects and its result is unused, so the JIT can remove the call through dead-code elimination, leaving an almost empty method. Fix 1: change the method to public int parse() { return Integer.parseInt(text); } so JMH consumes the returned value. Fix 2: keep void and add a Blackhole bh parameter, then call bh.consume(Integer.parseInt(text));.
Exercise
A benchmark computes Math.sqrt(a) and Math.cbrt(b) from two state fields and needs both results kept. Write the method signature and body.
Show answer
@Benchmark public void roots(Blackhole bh) { bh.consume(Math.sqrt(a)); bh.consume(Math.cbrt(b)); }. A method can return only one value, so the Blackhole keeps both results alive. The a and b values come from state fields so they are not constants.