Sub topic 7
Capturing Effectively Final Variables
This chapter assumes you can write local and anonymous classes, and that you know what a lambda expression is. It covers what a local or anonymous class may read from the method around it, why Java restricts that access, and how to work within the restriction.
What capture means
A local class or anonymous class is declared inside a method body. Its code can use the method's parameters and local variables as if they were in scope. This is called capturing a variable.
public class CaptureBasics {
static Runnable makeAdder(int base) {
int bonus = 5;
class Adder implements Runnable {
@Override
public void run() {
System.out.println(base + bonus);
}
}
return new Adder();
}
public static void main(String[] args) {
Runnable r = makeAdder(10);
r.run(); // 15
}
}makeAdder has already returned when r.run() executes. Its stack frame is gone, but run() still prints 15. The class cannot be reading the original variables. The values were copied into the Adder object when it was created.
The effectively final rule
Because the object holds a copy, the compiler must make sure the original and the copy can never disagree. Java does this with a rule. A captured local variable or parameter must be either:
- declared
final, or - effectively final, meaning it is never changed after it receives its value, even though it is not marked
final.
A variable is effectively final if it meets one of these conditions:
- It has an initializer and is never assigned again, and it is never the operand of
++or--. - It has no initializer, and every assignment happens while it is definitely unassigned. The variable is never assigned twice on any path.
The second case surprises people, so here is an example.
public class AssignOnce {
static Runnable describe(int n) {
String label;
if (n > 0) {
label = "positive";
} else {
label = "non-positive";
}
return () -> System.out.println(label);
}
public static void main(String[] args) {
describe(3).run(); // positive
describe(-1).run(); // non-positive
}
}label is assigned in two branches, but each path assigns it exactly once. The compiler accepts it as effectively final.
You do not need to add the final keyword. If you add final, the compiler checks your intent at the declaration instead of at the point of capture. Adding it is a matter of style.
The common error
The usual mistake is trying to update a local counter from inside a captured context.
public class CounterAttempt {
public static void main(String[] args) {
int count = 0;
Runnable r = new Runnable() {
@Override
public void run() {
// count++; // does not compile
}
};
r.run();
System.out.println(count); // 0
}
}If you uncomment count++, javac reports an error such as "local variables referenced from an inner class must be final or effectively final". Lambdas get the same message with "a lambda expression" in place of "an inner class".
A second form of the error happens when the variable is modified outside the class. Changing count anywhere in the method, even after the anonymous class, makes the variable not effectively final and breaks the capture.
Why Java chose copying
Java could have let the class share the variable with the method. It did not, for two reasons.
- A local variable lives on the thread's stack and disappears when the method returns. An object can outlive the method, so the object needs its own storage.
- A shared mutable local would be visible to several threads, because the object may run on a different thread. Locals have none of the visibility guarantees that fields can have through
volatileorsynchronized. Banning changes removes the whole problem class.
Languages such as JavaScript capture the variable itself and keep it alive on the heap. Java captures the value. This is why the restriction exists.
What can be captured
The rule applies to local variables and parameters only. Fields behave differently, as the following table shows.
| Name used inside the class | How it is accessed | May it change? |
|---|---|---|
| Local variable | Copied at creation | Not after capture (effectively final) |
| Method parameter | Copied at creation | Not after capture (effectively final) |
| Enhanced `for` variable | One fresh variable per iteration, copied | Not within the iteration |
| Classic `for` counter such as `i++` | Not effectively final | Cannot be captured directly |
| Instance field of the outer class | Read live through the outer reference | Yes |
| Static field | Read live | Yes |
Fields are not copied. The class reaches them through the enclosing instance (or the class name for static fields), so it sees current values and may assign them.
public class FieldVsLocal {
private int field = 1;
Runnable make() {
int local = 1;
Runnable r = () -> System.out.println(field + " " + local);
field = 2; // allowed: fields are read live
// local = 2; // would break capture of local
return r;
}
public static void main(String[] args) {
new FieldVsLocal().make().run(); // 2 1
}
}The lambda prints 2 1. The field update is visible, and the local was copied. Chapter material on the outer instance explains why: the captured object holds a reference to the FieldVsLocal instance and reads field through it.
Effectively final does not mean immutable
The rule protects the variable, not the object it points to. Reassigning the reference is forbidden, but calling methods on the object is fine.
public class Snapshot {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("a");
Runnable r = () -> System.out.println(sb);
sb.append("b");
r.run(); // ab
}
}The lambda holds a copy of the reference, and both references point to the same StringBuilder. The output is ab. If you wrote sb = new StringBuilder("z") anywhere in the method, the code would stop compiling.
This gap is the basis of every workaround.
Working around the restriction
When you need to change state from inside a captured context, put the state in an object, and capture the reference to that object.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Workarounds {
public static void main(String[] args) {
// 1. A mutable holder
AtomicInteger hits = new AtomicInteger();
Runnable counter = new Runnable() {
@Override
public void run() {
hits.incrementAndGet();
}
};
counter.run();
counter.run();
System.out.println(hits.get()); // 2
// 2. A one-element array
int[] total = {0};
Runnable adder = () -> total[0] += 10;
adder.run();
System.out.println(total[0]); // 10
// 3. A final copy of a loop counter
List<Runnable> tasks = new ArrayList<>();
for (int i = 0; i < 3; i++) {
final int id = i;
tasks.add(new Runnable() {
@Override
public void run() {
System.out.println("task " + id);
}
});
}
tasks.forEach(Runnable::run); // task 0, task 1, task 2
}
}Each approach has a cost:
AtomicIntegeris safe when several threads run the code, and it is the clearest choice.- A one-element array is short but gives no thread safety and hides intent from readers.
- Copying a counter into a new local, as in
id, is the right choice when you only need the current value. It is the standard fix for loops. - A field on the enclosing class also works, because fields are not captured. Use it when the state genuinely belongs to the object and not to one method call.
An enhanced for loop needs no copy. Its variable is a new local on each pass, so for (String s : names) tasks.add(() -> System.out.println(s)); compiles.
Timing: capture happens at creation
For an anonymous class, the copy is made when the new expression runs. For a local class, it is made when you create an instance with new Adder(), which can be later than the class declaration. Each instance gets its own copies. Two instances created in the same method call hold the same values only because the variables cannot change.
A local class also may not use a captured variable that is not definitely assigned at the point where the class is declared. Declare and assign the variable before the class body.
What the compiler generates
javac implements capture directly, in the way the copy model suggests. It adds a synthetic field to the nested class for each captured variable, with names like val$bonus, and adds matching parameters to the constructor. The expression new Adder() therefore passes the current values to a hidden constructor. You never write this code, but it explains the rules. The class only stores a value, so there is nothing to keep in sync, and the restriction makes that storage safe. A later chapter covers the generated class files in more detail.
Summary of rules
- Local and anonymous classes, and lambdas, can read enclosing locals and parameters only if they are final or effectively final.
- The value is copied at object creation, so the object works after the method has returned.
- The variable must not change anywhere in the method, either before or after the capture.
- Fields are read through the enclosing instance and may change freely.
- To simulate a changing local, capture a reference to a mutable object, or use a field.
Exercise
This method fails to compile. Explain why, and give two different fixes. static List<Runnable> build(int n) { List<Runnable> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(() -> System.out.println(i)); } return list; }
Show answer
The variable i is modified by i++ in the loop, so it is not effectively final and the lambda cannot capture it. Fix 1: copy it into a new local inside the loop, such as int id = i; and print id. Fix 2: use a form where each pass has its own variable, such as an enhanced for over a collection of numbers (for (int v : values)), or an IntStream.range(0, n).forEach(i -> list.add(() -> System.out.println(i))), where i is a parameter of the lambda and is never reassigned.
Exercise
In the following code, what does r.run() print, and why does it compile? int[] box = {1}; Runnable r = () -> System.out.println(box[0]); box[0] = 5; r.run();
Show answer
It prints 5. The variable box is never reassigned, so it is effectively final and can be captured. The lambda holds a copy of the reference, not a copy of the array contents. The assignment box[0] = 5 changes the array that both references point to, and the change is visible when run() executes.