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:

  1. Lambdas (Java 8). The compiler moves the lambda body into a hidden private static method, and invokedynamic calls LambdaMetafactory. At runtime it creates a hidden class that implements the functional interface. What comes out of this:
  • there are no Foo$1.class files 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.
  1. String concat (Java 9, JEP 280). a + b + c is no longer a StringBuilder chain but a StringConcatFactory call. The JDK picks the best strategy (computing the exact length up front, a single byte[]). Code compiled with Java 8 doesn't get this benefit, which is a note for libraries built with --release 8.

  2. Records (Java 16). equals, hashCode and toString are generated through the ObjectMethods bootstrap, so their bodies aren't in the .class file.

Besides these: switch pattern matching (SwitchBootstraps), and the new compilation of enum switches.

Practical consequences:

  • in a stack trace you see $$Lambda or lambda$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 on SerializedLambda and 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 invokedynamic correctly; 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.