Video in progress
In code with lots of proxies, decorators and interfaces, what can't the JIT optimize, and how do you measure it?
If a call site has one or two implementations, the JIT inlines it. With many implementations (a megamorphic call site) or calls through reflection, inlining stops. But this difference usually disappears against I/O, so measure with a profiler first.
📖 Answer
HotSpot records which classes arrive at each invokeinterface site. With one class (monomorphic) or two (bimorphic), C2 inlines directly with a type check. With three or more it is megamorphic (unless one class accounts for nearly all the calls), and the call goes through the vtable/itable with no inlining. And with no inlining, later optimizations are also shut off: escape analysis, removing unneeded checks.
Where patterns add cost:
- A strategy/decorator chain in a hot loop. For example, processing a million rows where
rule.apply()is called with 10 different classes. - A JDK dynamic proxy:
InvocationHandler.invoke, with arguments wrapped in anObject[]and primitives boxed. - Spring AOP: walking the interceptor chain on every call.
But let's be realistic: a typical REST request takes 5-50 ms, and the cost of a few proxy calls inside it is in microseconds. I've rarely seen a speedup from removing a proxy; I've seen many from removing an N+1 query or a wrong index.
How to measure:
# which methods were not inlined and why
java -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining -jar app.jar | grep "not inline"
# CPU profile, flame graph
asprof -d 30 -e cpu -f cpu.html <pid>
At the micro level, write the benchmark with JMH, otherwise JIT warm-up and dead code elimination distort the result. If you do find a real hot spot, the fix is usually to simplify the pattern right there (for example a switch over sealed types), not to give up on it across the whole codebase.
Sign up to mark studied questions and save your progress.