Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

Why can lambdas only capture local variables that are final or effectively final? How do people work around it, and what bugs do the workarounds cause?

A lambda copies the values of the local variables it uses when it is created, rather than referring to the variables themselves, because local variables live in a stack frame that may be gone by the time the lambda runs. If the variable could still change, the copy and the variable would disagree, and a lambda running on another thread would race with the code that changes it, so Java only allows final or effectively final locals. People work around it with one-element arrays or AtomicInteger holders, which hide shared mutable state and break under parallel streams and async code; the better fix is to restructure the code so the lambda returns values, for example with count(), sum() or collect().

Why this question is asked

Almost every Java developer has seen the error local variables referenced from a lambda expression must be final or effectively final, usually while trying to count something inside forEach. The quick fixes people find online make the error go away, but they often bring back the very bugs the rule was protecting against. Interviewers ask this question to see whether we understand the reason for the rule, not just the rule. In this answer, we will recap what effectively final means, see why lambdas copy values, reproduce the bug the common workarounds cause, and rewrite the code the way the language intends.

1A Quick Recap of Effectively Final

A local variable is effectively final if it is never assigned again after it is initialised. We do not have to write the final keyword; the compiler checks the code and treats the variable as final if nothing reassigns it. A lambda, and since Java 8 also an anonymous inner class, may only use local variables that are final or effectively final.

Java
String prefix = "order-"; // effectively final: never reassigned
ids.forEach(id -> System.out.println(prefix + id)); // fine: order-1, order-2
int count = 0;
ids.forEach(id -> count++);
// error: local variables referenced from a lambda expression must be final or effectively final
String label = "a";
label = "b"; // reassigned, so no longer effectively final
Runnable r = () -> System.out.println(label); // same error, even though the lambda only reads it

Notice the last case. The lambda only reads label, and still it does not compile, because label is reassigned somewhere in the method. The rule is about the variable, not about what the lambda does with it.

2Why Lambdas Capture Values, Not Variables

A local variable lives in the stack frame of the method that declares it. When the method returns, the frame is gone and so is the variable. A lambda, though, can outlive the method: we can return it, store it in a field, or hand it to an executor that runs it on another thread a second later. If the lambda referred to the variable itself, it would point into a frame that no longer exists.

So when a lambda is created, Java copies the current value of each local it uses into the lambda object, as a hidden field. The lambda then works with that copy forever. That copy is only correct if the variable can never change afterwards; otherwise the lambda's copy and the method's variable would quietly disagree. The effectively final rule makes that impossible, so there is only ever one value and no confusion about which one the lambda sees.

The rule also avoids a concurrency trap. If Java allowed changing captured locals, it would have to move them to the heap so several threads could share them, and then every lambda running in a parallel stream or on an executor would be updating the same variable without synchronisation. Local variables would stop being the one place in Java that is always thread-safe by construction.

3The Workarounds People Use

The two common tricks keep the variable itself effectively final while making the thing it points to mutable. A one-element array is the oldest: the array reference never changes, but its element does. AtomicInteger is the more respectable version.

Java
int[] count = {0};
ids.forEach(id -> count[0]++); // compiles: count itself is never reassigned
System.out.println(count[0]); // 3, correct for a sequential forEach
AtomicInteger total = new AtomicInteger();
ids.forEach(id -> total.incrementAndGet());
System.out.println(total.get()); // 3

Both compile, and in sequential code they give the right answer. But notice what they really do: they reintroduce shared mutable state, exactly what the compiler rule was designed to keep out of lambdas. The code now depends on the lambda running on one thread, at the time we expect, and nothing in the code says so.

4Where the Workarounds Break

Change forEach to a parallel stream, which is a one-word edit, and the array version gives wrong answers.

Java
int[] count = {0};
IntStream.range(0, 1_000_000).parallel().forEach(i -> count[0]++);
System.out.println(count[0]); // 412873 on one run, 389950 on the next: lost updates
Step throughTwo threads lose an update to count[0]
Thread 1count[0]Thread 2
read 41
read 41
write 42
write 42 (one increment lost)

4 messages in order. Play them, or step through them one at a time.

Both threads incremented, but the value grew by one.

count[0]++ is three steps: read the value, add one, write it back. Two threads can read the same value, both add one, and both write the same result, so one increment is lost. With many threads this happens constantly. AtomicInteger fixes the correctness, because incrementAndGet is atomic, but all threads now fight over one memory location, so the parallel version can be slower than a sequential loop.

Asynchronous code has a different failure. If a holder is filled in by a CompletableFuture callback, the method that reads it may run before the callback has happened, and see the initial value. Nothing fails; the result is simply wrong some of the time, depending on timing.

5The Better Fix: Return Values Instead of Mutating

The rule pushes us towards a different style: instead of having each lambda change a shared variable, we let the stream combine the results. Counting, summing and grouping are built in, and they are correct and fast in parallel because each thread works on its own part and the parts are combined at the end.

Java
long count = IntStream.range(0, 1_000_000).parallel().count(); // 1000000, every run
long n = ids.stream().filter(id -> id > 1).count(); // 2
int sum = orders.stream().mapToInt(Order::quantity).sum(); // no holder needed
Map<Status, Long> byStatus = orders.stream()
.collect(Collectors.groupingBy(Order::status, Collectors.counting()));
// {NEW=4, SHIPPED=7}

Notice that no variable is changed by any lambda. Each lambda only computes a value from its input, and the stream does the combining. This code is correct whether it runs sequentially, in parallel or later on another thread, and it says what it computes instead of how. When the logic really does need step-by-step mutation, a plain for loop with an ordinary local variable is the honest choice.

6Follow-up questions

Can a lambda change an instance field?

Yes. A lambda that uses a field captures this, and the field lives on the heap with the object, so it can be changed. But that is shared mutable state with the same risks: under a parallel stream or an executor, unsynchronised updates to the field race exactly like the array workaround.

Does effectively final make the object immutable?

No. It only prevents reassigning the variable. If a lambda captures an effectively final List, it can still call add on it, and doing that from a parallel stream is a race on an ArrayList. Collect into a new list instead.

Is AtomicInteger always a bad workaround?

Not always. For a counter that is shared on purpose between threads, such as a metric updated by many request handlers, AtomicInteger or LongAdder is the right tool. The problem is using it just to escape the compiler rule inside a computation that a reduction could express.

7Conclusion

In this answer, we saw that a lambda copies the values of the local variables it uses, because locals live in a stack frame that may be gone when the lambda runs. Allowing the variables to change would make the copy disagree with the variable and would create data races when lambdas run on other threads, so Java requires final or effectively final locals. One-element arrays and AtomicInteger holders get past the compiler but bring back shared mutable state, which breaks under parallel streams and async code. The better approach is to have lambdas return values and let count, sum, reduce or collect combine them.

What to say in the interviewAbout 90 seconds aloud

Open with

A lambda can only use local variables that are final or effectively final, meaning never reassigned after initialisation. The reason is how capture works. Local variables live in the method's stack frame, but a lambda can outlive the method, for example when it is returned or run later on an executor.

Then, if they want more

So when the lambda is created, Java copies the current values of the locals it uses into the lambda object. That copy is only safe if the variable cannot change; otherwise the lambda and the method would see different values, and if Java shared the variable instead, lambdas running on other threads would race on it without synchronisation.

The common workarounds are a one-element array, like int[] count = {0} and count[0]++, or an AtomicInteger holder. They compile because the reference itself is effectively final, but they bring back shared mutable state.

With a parallel stream the array version loses updates, because the increment is a read, add and write, so I get a different wrong count each run; AtomicInteger is correct but contended, and in async code the holder may be read before the callback runs.

The better fix is to restructure so lambdas return values: use count, mapToInt and sum, reduce or a collector like groupingBy with counting, or simply a for loop when mutation is natural.

About this answer

Last updated
12 November 2026
Versions it names
Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why can lambdas only capture local variables that are final or effectively final? How do...": https://scrivio-interview-library.netlify.app/java/lambdas/eef3be467b/