Video in progress
Is there only a syntax difference between a lambda and an anonymous class?
Anonymous class / Lambda — this: the anonymous object itself / the enclosing class's object; Scope: new: it can "shadow" an outer variable / not new: you can't declare a variable with the same name; Bytecode: Outer$1.class / invokedynamic + LambdaMetafactory, created at runtime; Instances: a new object on every new /…
📖 Answer
| Anonymous class | Lambda | |
|---|---|---|
this |
the anonymous object itself | the enclosing class's object |
| Scope | new: it can "shadow" an outer variable | not new: you can't declare a variable with the same name |
| Bytecode | Outer$1.class |
invokedynamic + LambdaMetafactory, created at runtime |
| Instances | a new object on every new |
if nothing is captured, usually one cached instance |
| State | can hold fields | can't |
| Type | any class/interface | only a functional interface |
What it affects in practice:
class Cache {
void schedule() {
executor.submit(() -> refresh()); // this = Cache
executor.submit(new Runnable() {
public void run() { refresh(); } // Cache.this is held implicitly
});
}
}
Both hold a reference to the outer Cache, if they use this. A lambda captures only what it actually uses, while an anonymous class (up to Java 18) always kept this. In long-lived callbacks, that can cause a memory leak.
The effectively final requirement is the same for both: the value of a captured local variable is copied, so changing it later is forbidden.
In a stack trace a lambda shows up as lambda$schedule$0: no name, so it's harder to debug. Move complex logic into a separate method and pass a method reference.
Sign up to mark studied questions and save your progress.