Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Capturing effectively final local variables

A lambda can capture a local variable without the `final` modifier if it is effectively final. A fixed reference does not make the object it points to immutable.

Version: Java SE 21

Syntax

Java SE 21: a lambda expression or an inner class can use an enclosing local variable or parameter only if it is final or effectively final. A captured local variable must also be definitely assigned before the lambda or inner-class body. For example: String prefix = "task "; Runnable task = () -> System.out.println(prefix);

In Java SE 21, a lambda or an inner class, including a local or anonymous class, can use an enclosing local variable or parameter only if it is final or effectively final. A local variable must also be definitely assigned before the lambda or inner-class body. This is effectively final local capture: the code gets the variable's value, not a writable slot, and a lambda can use that value after the enclosing method returns.

A local declared with an initializer but without final is effectively final if it never appears on the left-hand side of an assignment operator or as an operand of ++ or --. This includes assignments inside the initializer: int x = (x = 1); is legal, but x is not effectively final. Parameters are treated as initialized variables. Even x = x or x += 0 breaks this rule, including after lambda creation; trying to capture such a variable is a compile-time error. A non-final local declared without an initializer can be assigned in alternative branches and remain effectively final if, at each assignment, it is both definitely unassigned and not definitely assigned after the right-hand operand, and it never appears as an operand of ++ or --. It must still be definitely assigned before capture.

You cannot capture the index i of a basic for loop that updates it with i++. Make a per-iteration copy with final int id = i; inside the loop. An enhanced for has a separate variable for each iteration, so you can capture it if it remains final or effectively final.

For a reference type, the captured value is the reference, not a copy of the object. ++acc[0] changes an array element without reassigning acc. Object fields and shared static fields follow their own rules, not the local-capture rule. final does not provide thread safety: coordinate access to shared mutable state, for example by guarding every access to that state with the same lock.

Examples

public class CaptureDemo {
    static Runnable[] makeTasks() {
        String prefix = "task ";
        final int[] acc = {0};
        Runnable[] tasks = new Runnable[2];

        for (int i = 0; i < tasks.length; i++) {
            final int id = i;
            tasks[i] = () -> System.out.println(prefix + id + ": " + ++acc[0]);
        }
        return tasks;
    }

    public static void main(String[] args) {
        Runnable[] tasks = makeTasks();
        tasks[0].run();
        tasks[1].run();
    }
}

Result

task 0: 1
task 1: 2

`prefix` is effectively final, while `id` and `acc` are explicitly `final`. After `makeTasks()` returns, each task uses its own `id`, but both increment the same `acc[0]`. The tasks run in order on one thread.

Related lessons

  • Java · Lesson 22 · Advanced · Version: 2
  • Java · Lesson 34 · Advanced · Version: 2
  • Java · Lesson 36 · Advanced · Version: 2
  • Java · Lesson 8 · Intermediate · Version: 2

Sources