Sub topic 9
Profiling: what the JVM learns while running
This chapter assumes you know the tier levels 0 to 4 and how invocation and back-edge counters trigger compilation. It also assumes you can read basic -XX:+PrintCompilation output. Here you will learn what the JVM records about your program, where it records it, and how later chapters use it for inlining and speculative optimization.
Why profile at all
Bytecode alone doesn't say how a program behaves. A method may contain an if that is almost never true, or a call to an interface method that in practice always reaches one class. A static compiler such as javac can't know this. HotSpot can observe it, because the program is already running.
HotSpot records these observations as a profile. The profile is not a separate tool you start. It is data the interpreter and the C1 compiler collect while running your code, and the C2 compiler reads that data when it compiles.
Where the profile lives
Each profiled method gets a native-memory structure called a MethodData object (often shortened to MDO). It holds counters and small tables laid out to match the method's bytecode. The MDO is created lazily, when the method becomes warm enough to be worth profiling. Cold methods never get one.
Three kinds of code write into the MDO:
| Executor | Tier | Profiling behavior |
|---|---|---|
| Interpreter | 0 | Records profile data once an MDO exists |
| C1 with limited profiling | 2 | Records only invocation and back-edge counters |
| C1 with full profiling | 3 | Records counters, branches, and type information |
| C1 without profiling | 1 | Records nothing |
| C2 | 4 | Records nothing. It only reads the profile |
Tier 3 code is slower than tier 1 or 2 code, because it contains extra instructions that update the MDO on every branch and call. That cost is the reason the tier-transition rules from the previous chapters send a method to tier 2 when the C2 queue is long, and to tier 3 when C2 has room. A tier 3 method is meant to stay there only briefly.
What gets recorded
The profile has four main kinds of information.
- Counts. How many times a method was invoked and how many times each loop back-edge was taken. The previous chapters used these for hotness detection.
- Branch frequencies. For each conditional branch (
if,switch, loop condition), how often it was taken and how often it fell through. - Receiver types. At each virtual or interface call site, and at
instanceofandcheckcastbytecodes, which classes were actually seen. - Null and exception observations. Whether a null was ever seen at a null-checked spot, and whether an operation such as a bounds check or array store ever failed.
HotSpot can also record the types of arguments and return values at some call sites. This is controlled by the TypeProfileLevel flag. You rarely need to change it.
Type profiles are small
Type profiles do not keep an unbounded list of classes. Each call site holds a few rows (two by default, set by -XX:TypeProfileWidth), plus a counter for everything that didn't fit. After that, a call site is classified like this:
- Monomorphic. One receiver class was seen.
- Bimorphic. Two classes were seen.
- Megamorphic. More classes were seen than the rows can hold.
Later optimizations use these categories. The compiler can optimize a monomorphic or bimorphic site aggressively. It usually can't optimize a megamorphic one.
A profile is a statement about the past
The profile describes what happened up to the moment of compilation. C2 treats it as a prediction of the future. Its quality depends on two things.
- Enough data. C2 compiles only after the counters reach thresholds, which gives the profile time to settle. Counts that are too small are unreliable.
- Representative data. If the program changes behavior later, the profile is stale. This is the case the next chapters cover under speculative optimization and deoptimization.
The dotted line is the subject of a later chapter. When a profile-based assumption turns out to be false, execution falls back to the interpreter.
Profile pollution
An MDO belongs to a method, not to a caller. Suppose a shared helper such as describe(Shape s) calls s.area(). The call site inside describe records the types from every caller combined. If one part of the program passes only Square and another passes Circle, Triangle, and Hexagon, the site becomes megamorphic for everyone. This is called profile pollution.
The practical result is that the same loop can be fast or slow depending on unrelated code elsewhere. Inlining the helper into each caller can separate the profiles again, since an inlined copy is compiled in its caller's context, but only if the compiler chooses to inline it.
Observing the effect
The program below calls one interface method through a shared helper. It does this in three phases, with one, two, and then five receiver classes.
public class ProfilePhases {
interface Op { int apply(int x); }
static final class Inc implements Op { public int apply(int x) { return x + 1; } }
static final class Dbl implements Op { public int apply(int x) { return x * 2; } }
static final class Neg implements Op { public int apply(int x) { return -x; } }
static final class Sqr implements Op { public int apply(int x) { return x * x; } }
static final class Zero implements Op { public int apply(int x) { return 0; } }
static int run(Op op, int x) {
return op.apply(x);
}
static long phase(Op[] ops, int rounds) {
long start = System.nanoTime();
int acc = 0;
for (int i = 0; i < rounds; i++) {
acc += run(ops[i % ops.length], i);
}
long elapsed = System.nanoTime() - start;
System.out.println(ops.length + " type(s): " + elapsed / 1_000_000 + " ms (acc=" + acc + ")");
return elapsed;
}
public static void main(String[] args) {
Op[] one = { new Inc() };
Op[] two = { new Inc(), new Dbl() };
Op[] five = { new Inc(), new Dbl(), new Neg(), new Sqr(), new Zero() };
phase(one, 50_000_000);
phase(two, 50_000_000);
phase(five, 50_000_000);
}
}Compile and run it normally. Then look at the compiler's decisions with a diagnostic flag:
javac ProfilePhases.java
java ProfilePhases
java -XX:+PrintCompilation ProfilePhasesEach phase usually takes longer than the one before, but the exact numbers depend on your machine and JVM build. The PrintCompilation output will likely show ProfilePhases::run or ProfilePhases::phase compiled again after the later phases begin. Treat this as an illustration of the idea, not a benchmark. Chapter material on warmup explains why a single run like this can't give reliable timings.
Common errors
- Assuming profiling is free. Tier 3 code is measurably slower than tier 1 or 2 code. A method stuck at tier 3 because the C2 queue is backed up can hurt throughput.
- Assuming the profile is per call chain. It is per method (and per bytecode inside it), so unrelated callers can pollute each other.
- Testing with unrepresentative data. If a test or benchmark exercises only one receiver type, the JVM will optimize for that type. Production traffic with more types will then run differently.
- Expecting a megamorphic site to be broken. It still works correctly. It just uses a normal virtual call instead of an inlined fast path.
Summary
- Profiles are stored in a per-method MethodData object, written by the interpreter and by tier 3 code.
- They hold counts, branch frequencies, receiver types, and null and exception observations.
- Type profiles are bounded, which gives the monomorphic, bimorphic, and megamorphic classification.
- C2 reads the profile and treats it as a prediction. That prediction is the basis for inlining and speculative optimization in the next chapters.
Exercise
A helper method static double areaOf(Shape s) { return s.area(); } is called from module A with only Square objects and from module B with Circle, Triangle, and Hexagon objects. Module A's code runs slower than it did before module B was added. Explain why, using the profile, and name one way a compiler could restore module A's speed.
Show answer
The call site s.area() lives inside areaOf, and its type profile belongs to that method, so it records the receivers from both modules. With four classes seen, which exceeds the default two profile rows, the site is megamorphic and the compiler can't treat it as a single known target. This is profile pollution. If areaOf is inlined into module A's caller, the inlined copy is compiled with that caller's context, so the call there can again be treated as monomorphic and optimized.
Exercise
Why does the JVM run a method at tier 3 instead of going straight from the interpreter to C2, and what is the cost of tier 3?
Show answer
C2 needs profile data (branch frequencies, receiver types, null observations) to optimize well. Tier 3 is C1-compiled code with full profiling, so it collects that data faster than the interpreter while running much faster than interpreting. The cost is that its extra profile-update instructions make it slower than tier 1 or tier 2 code, so a method should spend only a short time there.