Sub topic 16
Under the Hood: invokedynamic and Lambda Identity
You have written many lambdas in this tutorial. This chapter looks at what the Java compiler and the JVM do with them. You do not need this knowledge to use lambdas. It does explain some behavior that can surprise you, such as why two lambdas that look the same are not == to each other.
Two Words You Need First
Bytecode is the set of low-level instructions that javac writes into a .class file. The JVM (Java Virtual Machine) reads and runs these instructions.
invokedynamic is one bytecode instruction. It was added in Java 7, and Java 8 began using it for lambdas. Most call instructions tell the JVM exactly which method to call. invokedynamic works differently. It tells the JVM to ask a helper method what to do the first time the instruction runs.
That helper is the bootstrap method. For lambdas, the bootstrap method lives in a JDK class called LambdaMetafactory.
How an Anonymous Class Compiles
Start with the older approach so you have something to compare against. Here is a small program with an anonymous class:
public class AnonDemo {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello from anonymous class");
}
};
r.run();
}
}Compile it:
javac AnonDemo.java
ls *.classYou will see two files: AnonDemo.class and AnonDemo$1.class. The compiler wrote a whole extra class for the anonymous Runnable. Every anonymous class in your code adds another .class file to your program. The JVM has to find and load each of those files.
How a Lambda Compiles
Now write the same program with a lambda:
public class LambdaDemo {
public static void main(String[] args) {
Runnable r = () -> System.out.println("Hello from lambda");
r.run();
}
}javac LambdaDemo.java
ls *.classThis time there is only LambdaDemo.class. The compiler did two things instead of writing a new class:
- It moved the lambda's body into a new private method inside
LambdaDemo. This method has a made-up name such aslambda$main$0. A method the compiler creates for you like this is called a synthetic method. - Where your lambda appeared, it put a single
invokedynamicinstruction.
You can see both with javap, a tool that ships with the JDK. The -c option prints bytecode, and -p includes private members:
javap -c -p LambdaDemoThe output looks roughly like this. Constant-pool numbers vary between JDK versions.
public static void main(java.lang.String[]);
Code:
0: invokedynamic #7, 0 // InvokeDynamic #0:run:()Ljava/lang/Runnable;
5: astore_1
6: aload_1
7: invokeinterface #11, 1 // InterfaceMethod java/lang/Runnable.run:()V
12: return
private static void lambda$main$0();
Code:
0: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #21 // String Hello from lambda
5: invokevirtual #23 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: returnThe println call now lives inside lambda$main$0. The main method no longer contains the lambda's code. It contains one instruction that says "give me a Runnable."
What Happens When the Program Runs
The first time the JVM reaches that invokedynamic instruction, it does not yet know how to produce a Runnable. So it calls the bootstrap method, LambdaMetafactory.metafactory. The bootstrap method:
- Creates a small class in memory that implements
Runnable. Itsrunmethod callslambda$main$0. - Wraps the recipe for making instances of that class in a call site. A call site is an object the JVM attaches to that one
invokedynamicinstruction. - Returns the call site to the JVM.
From then on, the JVM uses the stored call site directly. It does not call the bootstrap method again for that instruction.
Why Java Does It This Way
The Java designers chose this approach on purpose:
- Fewer files. A large program can contain thousands of lambdas. Without this design, each one would need its own
.classfile. - Work happens only when needed. A lambda's class is created the first time the code runs. Lambdas that never run cost almost nothing.
- Room to improve. The bytecode only says "ask the bootstrap method." Later JDK versions can change how lambda objects are built without anyone recompiling old code.
What Happens with Captured Variables
In the chapter on local variables, you learned that a lambda can capture an effectively final variable. Captured values become extra parameters of the synthetic method. For example:
import java.util.function.Supplier;
public class CaptureCompile {
public static void main(String[] args) {
String word = "hi";
Supplier<String> s = () -> word + "!";
System.out.println(s.get()); // hi!
}
}Here the compiler writes something like private static String lambda$main$0(String word). Each time the lambda expression runs, the JVM builds a new lambda object and stores the current value of word inside it. When you call get(), the object passes that stored value into the synthetic method.
This also explains the effectively-final rule. The lambda keeps a copy of the value, not a link to the variable. If Java let you change word afterward, the copy and the variable would no longer match.
If a lambda uses this or an instance field, the synthetic method becomes an instance method, and the lambda object stores a reference to this. That is why this inside a lambda means the enclosing object.
Lambda Identity: Do Not Use == or equals
Identity means "is this the very same object?" In Java, == checks identity for objects. For lambdas, identity follows rules you might not expect. Run this program:
import java.util.function.Supplier;
public class IdentityDemo {
static Runnable makeRunnable() {
return () -> System.out.println("run");
}
static Supplier<String> makeSupplier(String text) {
return () -> text;
}
public static void main(String[] args) {
Runnable r1 = makeRunnable();
Runnable r2 = makeRunnable();
System.out.println(r1 == r2); // true on HotSpot (the usual JVM), but not guaranteed
Supplier<String> s1 = makeSupplier("a");
Supplier<String> s2 = makeSupplier("a");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // false
Runnable r3 = () -> System.out.println("run");
System.out.println(r1 == r3); // false: different lambda expression in the source
System.out.println(r1.getClass().getName());
// Something like IdentityDemo$$Lambda/0x0000020001003a00 (varies by JDK)
}
}Each result has a reason:
r1 == r2istruebecause the lambda captures nothing. The JVM can reuse one object for every run of that expression, and HotSpot does. The Java specification allows this but does not promise it.s1 == s2isfalsebecause the lambda capturestext. Each run makes a new object to hold the captured value.s1.equals(s2)isfalsebecause lambda objects do not overrideequals. They use the identity check fromObject.r1 == r3isfalseeven though the code looks the same. Each lambda expression in your source code has its owninvokedynamicinstruction and its own class.
Here is the safe pattern:
import java.util.ArrayList;
import java.util.List;
public class ListenerDemo {
public static void main(String[] args) {
List<Runnable> listeners = new ArrayList<>();
Runnable onSave = () -> System.out.println("saved");
listeners.add(onSave);
System.out.println(listeners.remove(() -> System.out.println("saved"))); // false
System.out.println(listeners.remove(onSave)); // true
System.out.println(listeners.size()); // 0
}
}Anonymous Class vs Lambda at a Glance
| Question | Anonymous class | Lambda |
|---|---|---|
| Extra `.class` file on disk? | Yes, such as `Outer$1.class` | No |
| When is the class made? | At compile time | The first time the code runs |
| Where does the body go? | In the anonymous class | In a synthetic method such as `lambda$main$0` |
| New object every time? | Yes, always | Not always; non-capturing lambdas may be reused |
| What does `this` mean? | The anonymous object | The enclosing object |
| Readable `toString()`? | No | No |
Exercises
Exercise
You compile a class containing three anonymous classes and two lambdas. How many .class files does javac produce for this source file, and why?
Show answer
Four. One is the outer class and three are the anonymous classes (Outer$1, Outer$2, Outer$3). The two lambdas add no files. Their bodies become private synthetic methods in the outer class, and their classes are created in memory at run time by LambdaMetafactory.
Exercise
A Supplier<Integer> lambda captures a local variable named count. You call the method that creates it twice. Will the two Supplier objects be == to each other? Explain.
Show answer
No. The lambda captures a value, so each time the expression runs the JVM must create a new object to hold the captured count. Only non-capturing lambdas may be reused, and even that is a JVM choice rather than a guarantee.
Exercise
Why does listeners.remove(() -> refresh()) fail to remove a listener that was added earlier with listeners.add(() -> refresh())?
Show answer
Each lambda expression in the source produces its own object (and its own class), and lambdas do not override equals. The list's remove method compares with equals, finds no match, and returns false. Save the lambda in a variable and pass that same variable to both add and remove.