Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the keyword final have any impact on the JVM? [duplicate]

Now, I recently ran into a recommendation that you should use the keyword final as wide as possible. This is good in order to prevent a programmer from shooting his own leg - that is, reassign the variable that should not be reassigned.

But, does it serve any other goal? That is, can JVM use information about the final variables in order to optimize the bytecode somehow, so it would ran faster (build a better pipelining or use it in a multithreaded environment)? Or is just a syntactic sugar that minimizes the possibility of errors during code development?

like image 457
SPIRiT_1984 Avatar asked May 28 '15 12:05

SPIRiT_1984


2 Answers

IBM states:

Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.

like image 179
MKorsch Avatar answered Oct 26 '22 23:10

MKorsch


As far as variables go, Java is smart enough to figure that a variable is not being changed anywhere in the method, and use this knowledge for optimization purposes. It does not need you to mark a variable final in order to know that.

Methods are a slightly different story: when you mark a method final, Java can invoke such method faster, because it no longer needs to check for its overrides. Still, hotspot is smart enough to figure out that there are no overrides, with or without the use of final.

Generally, though, this recommendation is intended to make your code easier to read and understand by others: making a variable final tells you readers that you are making a constant; making a class final tells your readers that the class is not designed for inheritance; making a method final tells your readers that the logic of that method should stay invariant across the inheritance hierarchy. In the long run, this information is more valuable than the potential to optimize your running code.

like image 20
Sergey Kalinichenko Avatar answered Oct 26 '22 22:10

Sergey Kalinichenko