Chota Bheem
Chota Bheem

Reputation: 1116

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

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.

Upvotes: 2

Views: 107

Answers (1)

Holger
Holger

Reputation: 298153

Your first example is not valid syntax due to the wrong brackets. But you can omit them anyway:

//don't do this - race conditions!
library.stream().forEach(b -> pageCounter+=b.getPageCount());
//formally correct but inefficient and ugly
library.stream().forEachOrdered(b -> pageCount+=b.getPageCount());

Both are valid syntax and will compile, if pageCount is a mutable field, either an instance field or a static field, but, of course, the book is right, neither is recommended.

The restriction for captured variables to be either, final or effectively final, applies only to local variables (including parameters).

Upvotes: 4

Related Questions