Video in progress
How does a lambda work inside the JVM, and how does it differ from an anonymous class?
An anonymous class compiles to a separate .class file and is created with new on each call. A lambda body becomes a private synthetic method in the same class, an invokedynamic sits at the call site, and LambdaMetafactory creates the implementation class at runtime on the first call.
📖 Answer
If you look at the compiled result with javap -c -p:
Runnable r = () -> System.out.println("salom");
a method private static void lambda$main$0() appears in the class, and an invokedynamic instruction sits where r is created. When it executes for the first time, the bootstrap method (LambdaMetafactory.metafactory) generates a hidden class that implements Runnable and links it to the CallSite. Later calls go straight through.
Practical differences:
- Allocation. A lambda that captures nothing is a singleton: the same object comes back every time. A lambda that captures a local variable or
thiscreates a new object on every evaluation. An anonymous class is always a new object. - The meaning of
this. Inside a lambda,thisis the enclosing class. In an anonymous class it is the anonymous object itself. - Memory leaks. An anonymous inner class traditionally keeps a reference to the outer
this, even if it doesn't use it (since Java 18 javac drops an unusedthis$0field, but older bytecode and serializable classes still have it). A lambda captures it only if it uses it. This matters for long-lived listeners. - Startup cost. The first
invokedynamicbootstrap takes a little time; in a big application with many lambdas it can be noticeable at startup. That is why lambdas are not used in some places in the JDK itself.
Names like lambda$process$3 showing up in a stack trace also come from this mechanism: the number indicates the lambda's order inside the class.
Sign up to mark studied questions and save your progress.