Video in progress
What is invokedynamic, and why do lambdas, String concatenation and record methods run through it?
invokedynamic is a bytecode instruction whose call target is linked on first execution through a bootstrap method. That lets the JDK move the strategy from the compiler to the runtime: the lambda class, String concat and the record equals/hashCode can get faster on a newer JDK without recompiling.
📖 Answer
With an ordinary invokevirtual, the compiler writes the exact class and method into the bytecode. With invokedynamic, only a "bootstrap method" and its arguments are written. On the first call the JVM calls the bootstrap, which returns a CallSite, and later calls go straight to it. For the JIT, that's an ordinary call that can be inlined.
Three important users:
- Lambdas (Java 8). The compiler moves the lambda body into a hidden
private staticmethod, andinvokedynamiccallsLambdaMetafactory. At runtime it creates a hidden class that implements the functional interface. What comes out of this:
- there are no
Foo$1.classfiles like with anonymous classes, so the JAR is smaller; - a lambda that captures nothing is a single singleton object;
- the JDK later changed the strategy (hidden classes, Java 15) without recompiling.
-
String concat (Java 9, JEP 280).
a + b + cis no longer aStringBuilderchain but aStringConcatFactorycall. The JDK picks the best strategy (computing the exact length up front, a singlebyte[]). Code compiled with Java 8 doesn't get this benefit, which is a note for libraries built with--release 8. -
Records (Java 16).
equals,hashCodeandtoStringare generated through theObjectMethodsbootstrap, so their bodies aren't in the.classfile.
Besides these: switch pattern matching (SwitchBootstraps), and the new compilation of enum switches.
Practical consequences:
- in a stack trace you see
$$Lambdaorlambda$process$0: that's the name of the hidden method; - the first call is slower (bootstrap, class generation). In an application with many lambdas it affects startup; CDS/AppCDS archives cache this;
- you can make a lambda
Serializable, but it depends onSerializedLambdaand the hidden method name, so if the code changes, deserialization breaks. Don't serialize lambdas; - agents that work with bytecode (APM, coverage) have to handle
invokedynamiccorrectly; old versions fell over here.
From an architecture standpoint, the idea is a good one: the language semantics stay fixed, and the implementation stays with the platform.
Sign up to mark studied questions and save your progress.