Effectivitly Final Variable in Java Lambda - Mastering Lambdas by Maurice Naftalin

Viewed 97

While reading Mastering Lambdas by Maurice Naftalin, I came across following example. Chapter 3, Section 3.2.4 here are the two examples.

//don't do this - race conditions!
library.stream().forEach(b -> pageCounter += b.getPageCount());

Another one

//formally correct but inefficient and ugly
library.stream().forEachOrdered(b -> { pageCount+=b.getPageCount();});

My confusion was the reason given for not writing the above code. As lambdas are not suppose to chagne the state and can only access final or effectively final variables, how the above code can be valid in the first place?

Can somebody help me understand, if I am missing something.

Thanks in advance.

1 Answers
Related