Sub topic 11
Speculative optimization and uncommon traps
This chapter assumes you know Java classes, interfaces, methods, loops, and the basic idea that the JVM can compile frequently used bytecode while a program runs.
The JVM optimizes from observed behavior
The C2 compiler uses runtime profiling data. Profiling records facts such as:
- Which class usually reaches a virtual method call.
- Which branch is usually taken.
- Which values or types commonly appear.
- How often a method and its loops execute.
Suppose a method receives a Shape. During warmup, every call receives a Square. C2 can make a useful assumption: the call probably targets Square.area(). It can then inline the method and optimize the caller as if the receiver were a square.
This is speculative optimization. The compiler makes an optimization based on a prediction that is likely, but not guaranteed.
public class DeoptDemo {
interface Shape {
double area();
}
static final class Square implements Shape {
public double area() {
return 4.0;
}
}
static final class Circle implements Shape {
public double area() {
return 3.0;
}
}
static double run(Shape shape) {
return shape.area();
}
public static void main(String[] args) {
double total = 0.0;
Shape square = new Square();
for (int i = 0; i < 5_000_000; i++) {
total += run(square);
}
Shape circle = new Circle();
for (int i = 0; i < 5_000_000; i++) {
total += run(circle);
}
System.out.println(total);
}
}During the first loop, run sees only Square. The compiled version might effectively check that the object is a Square, then use the inlined square implementation. This is usually faster than performing a fully general virtual method lookup on every call.
When the second loop passes a Circle, the assumption becomes false.
Uncommon traps
An uncommon trap is a guarded path for a situation that profiling says is rare. The optimized code handles the common case directly. If the rare case occurs, the guard transfers control to JVM runtime machinery.
The JVM can then:
- Stop using the optimized machine code at that location.
- Reconstruct the program's interpreter or compiled state.
- Continue execution with a less specialized version.
- Record new profiling information.
- Compile a more general version if the new behavior becomes common.
This recovery process is called deoptimization. It does not mean the Java program failed. It means the JVM abandoned a prediction that no longer matched reality.
Why uncommon traps improve performance
A general implementation must handle every legal input. That can require repeated type checks, virtual dispatch, or branch handling. If one path dominates in practice, C2 can make that path short and fast while moving unusual cases out of the hot path.
Common speculative assumptions include:
| Assumption | Fast path | What can invalidate it |
|---|---|---|
| One receiver class dominates | Inline one method implementation | A different class appears |
| A branch is rarely taken | Optimize the frequent branch | The rare branch becomes frequent |
| A value is usually non-null | Remove some null-related work | A null value appears |
| A method has one effective target | Direct call or inline | Another implementation is loaded or used |
The JVM retains a fallback because Java semantics still require all valid cases to work.
Observing deoptimization
Compile and run the example with compilation logging:
javac DeoptDemo.java
java -XX:+PrintCompilation DeoptDemoThe output format depends on the JDK 11 build and timing. Look for entries related to DeoptDemo::run. A compiled entry may later be marked made not entrant, which means new calls should no longer enter that compiled version. A replacement compilation can then appear after the JVM collects more information.
Compilation logging is diagnostic rather than a stable application interface. Do not rely on one exact sequence of entries.
Practical guidance
Do not try to prevent every deoptimization. Occasional deoptimization is an expected part of adaptive compilation. Investigate it when it happens repeatedly in a hot operation or when performance changes after workload transitions.
When measuring code, include the phase in which the JVM has gathered representative profiles. A benchmark that measures only startup may mostly measure interpretation and compilation. A benchmark that warms up with squares and then measures circles may instead measure deoptimization and recompilation.
Exercise
In the example, why can the JVM optimize run(Shape) for Square without making the program incorrect when a Circle later appears?
Show answer
The JVM guards the specialized assumption. If a Circle reaches the code, an uncommon trap transfers execution to deoptimization and a general implementation, preserving Java's required behavior.