Video in progress
What is escape analysis, and which optimizations does the JIT do with it?
Escape analysis is the JIT working out that an object does not "escape" from the method or the thread. If it doesn't, the JIT doesn't create the object at all but spreads its fields into registers (scalar replacement), and removes unneeded locks.
📖 Answer
double distance(double x1, double y1, double x2, double y2) {
Point a = new Point(x1, y1);
Point b = new Point(x2, y2);
return a.distanceTo(b);
}
a and b are not stored anywhere, not handed to another thread, not returned. After inlining distanceTo, C2 sees that these two objects are unnecessary and compiles the code as if it were written with four doubles. Nothing is created on the heap and there is no load on the GC.
The optimizations:
- scalar replacement: the object is split into fields and lives in registers or on the stack;
- lock elision:
synchronizedon an object that only one thread sees is removed (for example, a localStringBuffer).
The limits that matter in practice:
- all of it depends on inlining. If a method is too big or the call is polymorphic, it won't be inlined and the object counts as "escaped";
- if an object escapes only on some branches, C2 often creates it anyway (Graal handles this case better);
- the interpreter and C1 don't have this optimization, so measuring a benchmark without warm-up gives wrong conclusions.
To check the effect: measure gc.alloc.rate.norm in JMH with -prof gc, then compare with -XX:-DoEscapeAnalysis.
Sign up to mark studied questions and save your progress.