Sub topic 7
Capturing Effectively Final Variables
This chapter assumes you can write basic Java classes and methods, understand local variables and scope, and use interfaces such as Runnable. It also assumes you know that an anonymous class is a class expression without a declared class name.
A local class or anonymous class can use a local variable or method parameter from the surrounding method. This is called capturing the variable. Java permits this only when the variable is final or effectively final.
A final variable is assigned once with the final keyword. An effectively final variable does not use final, but its value is never changed after its initial assignment.
public class CaptureDemo {
static Runnable makeGreeter(String name) {
String prefix = "Hello, "; // effectively final
class Greeter implements Runnable {
@Override
public void run() {
System.out.println(prefix + name);
}
}
return new Greeter();
}
public static void main(String[] args) {
Runnable greeter = makeGreeter("Ada");
greeter.run();
}
}The Greeter object uses both prefix and name, even though makeGreeter has already returned when run() is called. Java makes the captured values available to the returned object.
The code would stop compiling if either variable were reassigned:
// name = "Grace"; // no longer effectively final
// prefix = "Hi, "; // no longer effectively finalThe restriction prevents confusing behavior. A local variable normally belongs to a method invocation and may disappear when that method returns. A captured value must therefore behave like a stable value that the nested object can retain.
For example, a captured list can be changed because the list reference itself is not reassigned:
import java.util.ArrayList;
import java.util.List;
public class MutableCapture {
public static Runnable makeTask() {
List<String> names = new ArrayList<>();
return new Runnable() {
@Override
public void run() {
names.add("Ada");
System.out.println(names);
}
};
}
public static void main(String[] args) {
Runnable task = makeTask();
task.run();
task.run();
}
}Here, names remains effectively final, but the list changes from one call to the next. This is legal, although shared mutable state can make code harder to reason about.
The same capture rule applies to lambda expressions. A lambda can capture a local variable only when that variable is final or effectively final.
A common workaround for changing values is to place the value inside a mutable holder, such as an array or an object. Use that technique carefully. It can hide state changes and introduce concurrency problems. Prefer passing a value as a method argument or designing a separate state object when changing state is part of the design.
Exercise
Why does int count = 0; count++; prevent count from being captured by a local class?
Show answer
The increment changes the variable after its initial assignment, so count is not effectively final. Use a separate mutable object when shared changing state is truly required.