Lambda capture
What you will learn
A lambda can use values from the surrounding method or object. This is called capture. Local variables captured from an enclosing scope must be final or effectively final, but a referenced object can still be mutable. Understanding that distinction prevents accidental shared state.
- Determine which local variables can be captured.
- Explain how a captured object can change without reassigning its reference.
- Distinguish lambda this from anonymous-class this.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Create a reusable threshold rule
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { int minimum = 5; IntPredicate enough = units -> units >= minimum; System.out.println(enough.test(4)); System.out.println(enough.test(5)); }}Expected output:
falsetrueminimum is effectively final. The comparison includes the boundary value.
Rules and mental model
A local variable is effectively final when its assignments satisfy the language’s final-variable rules even though it is not declared final. For a local with an initializer, that usually means it is not subsequently assigned or incremented. Captured local variables must also be definitely assigned before use. A lambda can outlive the method that created it; a captured local is not a live writable alias to the caller’s local slot. Capturing a reference copies the reference value, not the referenced object. Mutating a captured list is legal; reassigning the captured list variable is not. Instance and static fields do not have the same effectively-final restriction, so a lambda reading an instance field can observe later updates to that field. Shared mutable state still needs appropriate synchronization when accessed concurrently.
A lambda does not introduce a new meaning of this; it uses the enclosing context. An anonymous class does introduce its own instance, so this there refers to the anonymous object. A lambda parameter cannot redeclare an enclosing local variable of the same name. An ordinary for-loop counter that increments is not effectively final; introduce a fresh local per iteration if you need to capture that iteration’s number. An enhanced for-loop variable is separately initialized for each iteration and may be captured if not reassigned. Avoid treating lambda identity, caching or allocation as a portable guarantee.
Observe a change in a captured object
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { List<String> names = new ArrayList<>(); Supplier<Integer> size = () -> names.size(); names.add("pen"); System.out.println(size.get()); names.add("book"); System.out.println(size.get()); }}Expected output:
12The captured reference stays the same while the list contents change. The supplier reads its current size each time.
Capture a fresh value for each callback
import java.util.*;import java.util.function.*;public class Main {
public static void main(String[] args) { List<IntSupplier> jobs = new ArrayList<>(); for (int i = 0; i < 3; i++) { int ticket = i + 10; jobs.add(() -> ticket); } for (IntSupplier job : jobs) System.out.println(job.getAsInt()); }}Expected output:
101112ticket is a fresh effectively-final local for each iteration. Each supplier returns its own captured value.
Compare lambda and anonymous class receivers
import java.util.*;import java.util.function.*;public class Main { String name = "outer"; void show() { Supplier<String> lambda = () -> this.name; Supplier<String> anonymous = new Supplier<String>() { final String name = "inner"; public String get() { return this.name; } }; System.out.println(lambda.get()); System.out.println(anonymous.get()); } public static void main(String[] args) { Main app = new Main(); app.show(); }}Expected output:
outerinnerThe lambda uses the enclosing Main receiver. The anonymous class supplies its own field and receiver.
Common mistakes
Do not use a mutable one-element array merely to bypass the capture rule; it introduces shared mutable state. Prefer returning a result or using an explicit owner for state.
Practice
Implement static IntPredicate atLeast(int limit) returning a predicate using the supplied limit. Create rules for 3 and 7; call each with 5, then call the second with 7. Print the three boolean results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lambda capture — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
A lambda reads `int limit = 5;` and limit is later incremented. What happens?
A captured ArrayList receives an element after callback creation. What can a later size callback observe?
What does this denote in a lambda in an instance method?
How can a regular for-loop create callbacks with distinct iteration values?
Does a final list reference make its contents immutable?