To my understanding, lambda expressions capture values, not the variables. For example, the following is a compile-time error:
for (int k = 0; k < 10; k++) {
new Thread(() -> System.out.println(k)).start();
// Error—cannot capture k
// Local variable k defined in an enclosing scope must be final or effectively final
}
However when I try to run the same logic with enhanced for-loop
everything is working fine:
List<Integer> listOfInt = new Arrays.asList(1, 2, 3);
for (Integer arg : listOfInt) {
new Thread(() -> System.out.println(arg)).start();
// OK to capture 'arg'
}
Why is it working fine for an enhanced for
loop and not for a normal conventional for
loop, although the enhanced for
loop is also somewhere inside incrementing the variable as done by a normal loop.**
Lambda expressions work like callbacks. The moment they are passed in the code, they 'store' any external values (or references) they require to operate (as if these values were passed as arguments in a function call. This is just hidden from the developer). In your first example, you could work around the problem by storing
k
to a separate variable, like d:Effectively
final
means, that in the above example, you can leave the 'final' keyword out, becaused
is effectively final, since it is never changed within its scope.For
loops operate differently. They are iterative code (as opposed to a callback). They work within their respective scope and can use all variables on their own stack. This means, that thefor
loop's code block is part of the external code block.As to your highlighted question:
An enhanced
for
loop does not operate with a regular index-counter, at least not directly. Enhancedfor
loops (over non-arrays) create a hidden Iterator. You can test this the following way:The above example will cause a ConcurrentModificationException. This is due to the iterator noticing that the underlying collection has changed during the execution. However in your very example, the external loop creates an 'effectively final' variable
arg
which can be referenced within the lambda expression, because the value is captured at execution time.The prevention of the capture of 'non-effectively-final' values is more or less just a precaution in Java, because in other languages (like JavaScript e.g.) this works differently.
So the compiler could theoretically translate your code, capture the value, and continue, but it would have to store that value differently, and you would probably get unexpected results. Therefore the team developing lambdas for Java 8 correctly excluded this scenario, by preventing it with an exception.
If you ever need to change values of external variables within lambda expressions, you can either declare a one-element array:
Or use Atomic<T> to make it thread-safe. However with your example, this would probably return "before" since the thread would most likely execute after the execution of println.
In an enhanced for loop the variable is initialized every iteration. From §14.14.2 of the Java Language Specification (JLS):
In other words, your enhanced for loop is equivalent to:
Since the variable is initialized each iteration it is effectively final (unless you modify the variable inside the loop).
In contrast, the variable in the basic for loop (
k
in your case) is initialized once and updated each iteration (if a "ForUpdate" is present, e.g.k++
). See §14.14.1 of the JLS for more information. Since the variable is updated each iteration is is not final nor effectively final.The need for a final or effectively final variable is mandated and explained by §15.27.2 of the JLS:
That last sentence even explicitly mentions the difference between basic for loop variables and enhanced for loop variables.
The other replies are helpful, but they don't seem to tackle the question directly and answer it in clear terms.
In your first example, you're trying to access
k
from the lambda expression. The problem here is thatk
changes its value over time (k++
is called after each loop iteration). Lambda expressions do capture external references, but they need to be marked asfinal
or be "effectively final" (i.e., marking them asfinal
would still produce valid code). This is to prevent concurrency problems; by the time the thread you created is run,k
could already hold a new value.In your second example, on the other hand, the variable you're accessing is
arg
, which is reinitialized with every iteration of the enhanced for-loop (compare with the example above, wherek
was merely updated), so you're creating an entirely new variable with each iteration. As an aside, you can also explicitly declare the iteration variable of an enhanced for-loop asfinal
:This ensures that the value
arg
references won't have changed by the time the thread you created is run.An enhanced
for
loop is defined to be equivalent to this code:This substitution code explains why the variable of an enhanced
for
loop is considered effectively final.