Sub topic 5
Long-running loops and on-stack replacement
This chapter assumes you know how the interpreter runs bytecode and how HotSpot uses invocation counters and back-edge counters to detect hot code. It also assumes you can run java with -XX flags. You do not need to know tiered compilation levels in detail yet. Here, a "tier" only means a compilation level.
The problem: a method that is called once
A method becomes a compile candidate when it is called often. That rule fails for a method that is called once and then loops for minutes. A typical case is main with a long for loop. Its invocation counter stays at 1, so the invocation trigger never fires.
If invocation counts were the only trigger, the loop would run in the interpreter until the method returned. The compiled code would be ready, but nothing would use it. This is what on-stack replacement (OSR) solves.
On-stack replacement is the technique of switching a running method from one kind of execution to another in the middle of that method's execution. In HotSpot, it switches an interpreter frame to a compiled frame while the loop is still running.
Two counters, two kinds of compilation
Each method has an invocation counter and a back-edge counter. A back-edge is a jump backward in the bytecode, which is how every loop iterates. The interpreter increments the back-edge counter on each jump.
| Trigger | Counter | Result | Entry point |
|---|---|---|---|
| Method called many times | Invocation counter (plus back-edges) | Normal compilation | Start of the method |
| Loop iterates many times | Back-edge counter | OSR compilation | A specific loop bytecode index |
With tiered compilation, the default tier 3 back-edge threshold (Tier3BackEdgeThreshold) is 60000. When the counter crosses it, the interpreter asks for an OSR compilation. The tier 4 equivalent (Tier4BackEdgeThreshold) is 40000. The interpreter does not check on every iteration. It checks when the counter crosses a notification boundary, so the exact moment varies a little.
The OSR request includes a bytecode index (bci). This is the offset of the loop header inside the method's bytecode. The compiler builds a version of the method whose entry point is that loop header, not the first instruction.
What happens during the switch
- The interpreter runs the loop and increments the back-edge counter.
- The counter crosses the threshold, and the interpreter sends a compile request that includes the bci.
- A background compiler thread compiles the method with an entry at that bci. The interpreter keeps running the loop meanwhile.
- When the compiled code is installed, the next back-edge that checks for it finds an OSR entry for that bci.
- The runtime migrates the frame. It copies the interpreter frame's local variables and held monitors (locks) into a compiled frame, then jumps into the compiled loop.
The loop's state is carried over, so the program cannot tell the difference. The loop variable i and the accumulator sum keep their values, and the loop continues from the next iteration.
Seeing OSR in PrintCompilation
Here is a program with exactly one long loop and one call to main:
public class OsrDemo {
public static void main(String[] args) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 200_000_000; i++) {
sum += i ^ (i >>> 3);
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println("sum=" + sum + " time=" + ms + " ms");
}
}Compile it and filter the compilation log for main:
javac OsrDemo.java
java -XX:+PrintCompilation OsrDemo | grep OsrDemoYou should see lines similar to the following. The timestamps, compile IDs, and bci will differ on your machine, so treat these as an illustration of the format:
85 45 % 3 OsrDemo::main @ 8 (52 bytes)
93 46 % 4 OsrDemo::main @ 8 (52 bytes)Read each line from left to right:
- The first number is the time in milliseconds since JVM start.
- The second number is the compile ID.
- The
%in the flags column marks an OSR compilation. A normal compilation has a blank there. - The next number is the tier (3 is C1 with full profiling, 4 is C2).
@ 8is the bci of the loop entry.
There is no line without % for main, because main was never called again. The method has no normal compiled version, only compiled versions of the loop.
Nested loops and which loop gets compiled
A method with nested loops can have several OSR entry points, one per loop header. The back-edge counter belongs to the method, not to a single loop. The compile request names the bci of the back-edge that triggered it.
- A hot inner loop is usually the one that triggers the request, because it produces the most back-edges.
- The OSR compilation for the inner loop still includes the enclosing code. Execution can leave the inner loop and continue through the outer loop in compiled code.
- If the method is later entered at the top again, for example in a second call, the interpreter uses the normal entry. A separate normal compilation is needed to make calls fast.
In the log, you may see the same method with several % lines at different bci values and tiers. That is normal.
Gotchas
OSR code is not always as good as normal code
When a method is compiled normally, the compiler knows the method starts at the top and can reason about every variable from its initial value. An OSR entry starts in the middle of the method, so the compiler knows less about the incoming locals. For example, it cannot assume a variable still has its starting value. Loop optimizations such as range check elimination may therefore have less to work with. A loop that runs well when it is in a method called repeatedly can run somewhat slower as an OSR compilation.
Benchmarks written in `main` can mislead
A common beginner benchmark puts the timed loop directly in main. You then measure interpreter time, C1 time, and C2 OSR time all together, with a compile in the middle. Moving the loop into a separate method and calling it several times gives normal compilations and a more representative result. The warmup chapter covers measurement in more detail.
Compile requests are asynchronous
The interpreter does not wait for the compiler. Between the request and the installation of the code, the loop continues to run slowly in the interpreter. On a busy machine or with a long compile queue, this window can be noticeably longer.
Deoptimization can send you back
OSR-compiled code can be deoptimized like any other compiled code. If a speculative assumption fails inside the loop, execution returns to the interpreter at the matching bytecode, and the back-edge counter may later trigger OSR again. Deoptimization is covered in its own chapter.
Flags for experimenting
| Flag | Effect |
|---|---|
| `-XX:+PrintCompilation` | Shows OSR compilations with a `%` flag and `@ bci` |
| `-XX:Tier3BackEdgeThreshold=N` | Changes the back-edge count that triggers tier 3 OSR |
| `-XX:Tier4BackEdgeThreshold=N` | Changes the back-edge count that triggers tier 4 OSR |
| `-XX:-UseOnStackReplacement` | Disables OSR, so a loop in a once-called method stays interpreted |
Try the last flag on OsrDemo and compare the printed time with the default run:
java OsrDemo
java -XX:-UseOnStackReplacement OsrDemoWith OSR disabled, main should never be compiled, and the run should be much slower. Use this flag for learning only. Do not disable OSR in production.
Exercise
A program calls process() once. Inside it, a loop runs ten million iterations. -XX:+PrintCompilation shows lines for process with a % flag and @ 14, but no line for process without a %. Explain what the % and @ 14 mean, and why there is no normal compilation.
Show answer
The % marks an on-stack replacement (OSR) compilation. The @ 14 is the bytecode index of the loop header where the compiled code can be entered. The method was called only once, so its invocation counter never reached the threshold for a normal compilation. The loop's back-edge counter did cross its threshold, which produced OSR compilations. A normal compiled version would only appear if process() were called more times.
Exercise
Why can timing a long loop directly inside main give a different result from timing the same loop moved into a method that you call many times?
Show answer
The loop in main runs first in the interpreter, then in OSR-compiled code. The OSR code is entered mid-method and may be less optimized than a normal compilation. The measurement therefore includes interpreter time and compile delay. A method called repeatedly is compiled through the normal path and, after warmup, is measured as fully compiled code.