1

When I'm using lambda expressions or anonymous inner classes, with variables from outer class, I often get the compile time error:

Lamba expressions:

local variables referenced from a lambda expression must be final or effectively final

Inner classes:

local variables referenced from an inner class must be final or effectively final


It means that compiler in Java 8 is able to deduce whether variable is implicitly final or not.
Regarding to this question, using final variables instead of non-final sometimes gives a huge positive impact on performance.
My question is:
Does compiler in java 8 interpret effectively final variables as final variables and later, in runtime use it as final?
In consequence, does it make the same optimization, as it's doing for the final variables?

Questions about differences between effective final and final (i.e. this) are connected with the reason why it has to be effectively final but doesn't say anything which answers my question.

I would be grateful for any answers.

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
Michał Szewczyk
  • 7,540
  • 8
  • 35
  • 47

2 Answers2

1

Does compiler in java 8 interpret effectively final variables as final variables and later, in runtime use it as final?

The answer will be yes in both cases.

The reason for the latter is that the class file format does not provide a way to say whether a local variable is declared as final. Therefore, if the JIT compiler is going to optimize based on finality, the finality must be inferred from what the bytecodes of a method actually do; i.e. effective finality.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

"Regarding to this question, using final variables instead of non-final sometimes gives a huge possitive impact on performance."

If I understand correctly the question you linked to, it really has nothing to do with "effectively final". The positive impacts you're referring to are for instance variables (that aren't private); declaring them final can be helpful because it means that the compiler can be sure that no method in a subclass can modify the variable.

"Effectively final" is a concept that applies only to local variables declared inside a method (including parameters). There's no possibility that a local variable in a method could be modified in a subclass.

Using the final keyword on local variables in a method might help with optimization, but a good compiler wouldn't need it. It would be able to tell that a variable doesn't change, and optimize accordingly. In fact, even if the variable isn't final, but the compiler can tell that it doesn't get modified for a certain stretch of code, a good compiler should be able to figure out that it isn't changed during that period, and make optimizations based on that.

ajb
  • 31,309
  • 3
  • 58
  • 84