Tuesday, July 18, 2017

why variables inside foreach loop of java8 should be final?

The Java Memory Model has very important property: it guarantees that local variables and method parameters are never writable by another thread. This adds much safety to multi-threading programming. However when you create a lambda (or an anonymous class), nobody knows how it will be used. It can be passed to another thread for execution (for example, if you use parallelStream().forEach(...)). Were it possible to modify the local variable that important property would be violated. Not the thing the Java language developers would sacrifice.

Usually when you are using lambdas, you are trying to program in functional way. But in functional programming mutable variables are considered bad practice: it's better to assign every variable only once. So trying to modify the local variable actually smells. Use various stream reduction methods instead of forEach to produce a good functional code.

https://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop
https://stackoverflow.com/questions/31801313/why-variables-inside-foreach-loop-of-java8-should-be-final



0 comments:

Post a Comment