Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

A benchmark consists of a single main method with a loop of one billion iterations timed with System.nanoTime. Explain on-stack replacement, and why this benchmark is misleading.

Because main runs only once, the JIT never compiles it on method entry; instead the loop's back-edge counter triggers on-stack replacement, a special compilation entered in the middle of the running loop, with the interpreter's state transferred into compiled frames. The benchmark is misleading for several reasons: the timed region mixes interpreted time, compilation and compiled time; OSR code is often less optimised than a normal compilation of the same hot code; and if the result is unused or the inputs are constant, the JIT can remove or fold the work so the loop looks faster than it is. JMH avoids these traps with warmup iterations, forked JVMs and consumed results.

Why this question is asked

Almost everyone writes this benchmark once: one main method, a long loop, two calls to System.nanoTime. The numbers look precise, and they are often wrong by a large factor, sometimes in either direction. Interviewers ask it to see whether we understand how the JIT treats such code and whether we know how to measure properly. In this answer, we will look at the benchmark, recap OSR and see how it applies here, go through each reason the result is misleading, and then rewrite it with JMH.

1The Benchmark in Question

Here is the typical version. It times a loop of one billion iterations that computes something cheap.

Java
public class Bench {
public static void main(String[] args) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 1_000_000_000; i++) {
sum += i * 3;
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("took " + ms + " ms"); // took 310 ms (example)
// sum is never used
}
}

At first sight this measures the cost of one billion multiplications and additions. It measures something quite different, and to see what, we need to know how this code gets compiled at all.

2A Quick Recap of On-Stack Replacement

HotSpot compiles a method once it has been invoked many times, and the compiled code is used from the next invocation onward. main is invoked once, so it never becomes hot by invocations, and the running invocation starts in the interpreter. What rescues it is on-stack replacement, OSR. The interpreter also counts back edges, the jumps back to the start of a loop, and when that counter passes a threshold the JIT compiles a special version of main that is entered at the loop header instead of at the start of the method.

When that version is ready, at the next back edge the interpreter copies the current values of the local variables, i, sum and start, into a buffer and jumps into the OSR code, which unpacks them into its own registers and continues the loop. This happens first with C1 and later with C2, so the loop runs at several different speeds during one measurement.

Step throughWhat happens inside the timed region
main (interpreter)JIT compilerOSR code
start timer, loop interpreted
back-edge threshold: request C1 OSR
C1 OSR version ready
transfer i, sum, start; continue loop
hotter: request C2 OSR
C2 OSR version replaces C1
finish loop, stop timer

7 messages in order. Play them, or step through them one at a time.

One measurement covers interpreted, C1 and C2 phases plus compilation time.

3Reason 1: The Measurement Mixes Phases

The timed region includes the interpreted iterations at the start, the time spent waiting for compilation, the C1 OSR phase and finally the C2 OSR phase. The result is an average of very different speeds, and it changes with the machine, the number of compiler threads and the JDK version. It does not tell us how fast the code runs once warm, nor how slow it is cold. Notice also that the result depends on the loop count: with 10 million iterations the interpreted part dominates; with 10 billion the C2 part dominates.

4Reason 2: OSR Code Is Not Normal Hot Code

OSR code has to be entered in the middle of a loop with state handed over from the interpreter. That constrains the compiler: it must accept the values as they arrive and cannot always apply the same loop optimisations it would to a method compiled from its start, such as some forms of loop unrolling, vectorisation or hoisting work out of the loop. So even the fast part of the measurement may be slower, or occasionally different in other ways, than the same code inside a method that is called many times and compiled normally, which is how hot code in a real application usually runs.

5Reason 3: Dead Code and Constant Folding

The JIT only has to preserve what the program can observe. In our benchmark, sum is never printed or stored anywhere, so its value is not observable. C2 is entitled to remove the computation of sum entirely, and then the loop does nothing, which it can remove too. This is dead code elimination. Similarly, if the inputs are constants known at compile time, the compiler can compute the result once, constant folding, or replace the loop with a closed-form formula. Either way, the time no longer reflects the work we meant to measure.

Java
long sum = 0;
for (int i = 0; i < 1_000_000_000; i++) sum += i * 3;
// sum unused: C2 may delete the loop -> 'took 0 ms' on some runs
System.out.println(sum); // 1499999998500000000
// now sum is observable, but the bounds and the formula are constants,
// so the compiler may still simplify the loop far beyond what real code allows
Why the main-method benchmark misleads
ProblemEffect on the numberHow JMH handles it
Interpreted and compile time in the timingtoo slow, unstablewarmup iterations before measuring
Only OSR code ever runsnot like real hot codebenchmark method called repeatedly
Unused resultwork deleted, too fastreturn value or Blackhole consumes it
Constant inputswork folded, too fastinputs read from @State fields
Profile from earlier testsdepends on test ordereach benchmark in a forked JVM

So the same benchmark can report a time that is too high, because of interpreted and OSR phases, or far too low, because the work was removed. Without looking at the generated code, we cannot tell which happened.

6Doing It Properly With JMH

JMH, the Java Microbenchmark Harness maintained by the OpenJDK project, is built to avoid exactly these problems. It calls the benchmark method repeatedly, so the method is compiled normally rather than through OSR. It runs warmup iterations whose results are discarded, so measurement starts after the JIT has done its work. It forks a fresh JVM for each benchmark, so profiles from one test do not affect another. And it consumes results: a value returned from a benchmark method, or passed to a Blackhole, is treated as observable, so the JIT cannot delete the work. Reading inputs from fields of a @State object prevents constant folding.

Java
@State(Scope.Thread)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public class SumBench {
int n = 1_000_000; // a field, not a constant: cannot be folded
@Benchmark
public long sum() { // returned value is consumed by JMH
long s = 0;
for (int i = 0; i < n; i++) s += i * 3;
return s;
}
}
// Benchmark Mode Cnt Score Error Units (example)
// SumBench.sum avgt 10 262.4 +- 3.1 us/op

The result now has a meaning: the average time per call of warmed, normally compiled code, with an error estimate across forks. When the result still looks surprising, JMH's profilers, for example -prof gc for allocation or the perfasm profiler on Linux, show what the JIT generated.

7Follow-up questions

How does PrintCompilation mark OSR compilations?

With a % sign in the attribute column, and with @ followed by the bytecode index of the loop header after the method name, for example 'Bench::main @ 6'. That index identifies the loop where the OSR code is entered. OSR compilations appear at level 3 for C1 and level 4 for C2, like normal ones.

Is it enough to add a warmup loop before the timed loop?

It helps a little but does not fix the main problems. The timed loop is still inside main, so it still runs as OSR code, the result may still be unused, and the warmup loop's profile may differ from the timed one. Putting the work in its own method and calling it many times is better, and JMH handles all the details we would otherwise get wrong.

When is a simple nanoTime measurement fine?

For coarse timings of large operations where JIT effects are small relative to the work, such as how long a batch import of a million rows takes end to end, or for logging the latency of real requests in production. For anything measured in nanoseconds or microseconds, use JMH.

8Conclusion

In this answer, we saw that a loop inside main is compiled only through on-stack replacement, triggered by back-edge counters, with interpreter state transferred into compiled frames mid-loop. The single timing mixes interpreted, C1 and C2 phases, measures OSR code that may be less optimised than real hot code, and can be distorted by dead code elimination and constant folding. JMH fixes this with warmup iterations, forked JVMs, normal compilation of a repeatedly called method, and consumed results.

What to say in the interviewAbout 90 seconds aloud

Open with

Since main is invoked only once, the JIT never compiles it the normal way, on method entry. The interpreter counts loop back edges, and when the counter passes a threshold the JIT does an on-stack replacement compilation: a version of main whose entry point is the loop header.

Then, if they want more

At the next back edge the interpreter copies the locals, i and sum, into a buffer and jumps into the compiled code, which continues the loop; first a C1 OSR version, later a C2 one. That is why the benchmark is misleading.

First, the timed region mixes interpreted iterations, compile time, C1 and C2 phases, so the number is an average of very different speeds and depends on the loop count.

Second, only OSR code ever runs, and OSR code is often less optimised than a normal compilation of a method that is called many times, which is how hot code runs in a real application.

Third, sum is never used, so C2 can remove the whole loop as dead code, and constant bounds let it fold or simplify the work, so the result can be far too fast.

I would use JMH: it calls the benchmark method repeatedly so it is compiled normally, runs warmup iterations, forks fresh JVMs so profiles do not leak, and consumes return values or uses a Blackhole so the work cannot be deleted.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A benchmark consists of a single main method with a loop of one billion iterations timed...": https://scrivio-interview-library.netlify.app/java/jit-compilation/55208525e6/