Video in progress
How does a lambda expression look in bytecode, and what role does invokedynamic play here?
The compiler turns the lambda body into a private synthetic method in the class and puts an invokedynamic at the call site. On first execution LambdaMetafactory creates a hidden class at runtime that implements the functional interface, and later calls reuse it.
📖 Answer
public class Demo {
Runnable r = () -> System.out.println("salom");
}
javap -c -p Demo shows two things:
private static void lambda$new$0(); // the lambda body
...
invokedynamic #7, 0 // InvokeDynamic #0:run:()Ljava/lang/Runnable;
invokedynamic calls a bootstrap method (LambdaMetafactory.metafactory) the first time the call site runs. It generates a hidden class that implements Runnable and returns a CallSite. After that the binding is fixed, and the JIT can inline it like an ordinary call.
Why not an anonymous class:
- every anonymous class is a separate
.classfile on disk and a class loaded at startup, while lambdas are created only when needed; - the JDK can change the strategy later without touching the compiled code;
- for a lambda that captures no outside variables, a single instance is reused, so there is no
newon each call.
Practical consequences: names like lambda$process$3 in stack traces come from this. In a big application with many lambdas the first calls slow startup a bit, and AppCDS can archive these classes too. The same invokedynamic mechanism is also used for string concatenation in Java 9+, for equals/hashCode of records in Java 16+, and for pattern matching switch in Java 21.
Sign up to mark studied questions and save your progress.