Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final methods are inlined?

Are Java final methods automatically inlined?

Many books says yes many books says no!!!

like image 753
xdevel2000 Avatar asked Nov 09 '09 13:11

xdevel2000


People also ask

What happens when method is final?

If we declare a method as final, then it cannot be overridden by any subclasses. And, if we declare a class as final, we restrict the other classes to inherit or extend it. In other words, the final classes can not be inherited by other classes.

Can final method be called?

Can We Override a Final Method? No, the Methods that are declared as final cannot be Overridden or hidden.

What is method inlining in Java?

What Method Inlining Is? Basically, inlining is a way to optimize compiled source code at runtime by replacing the invocations of the most often executed methods with its bodies. Although there's compilation involved, it's not performed by the traditional javac compiler, but by the JVM itself.

Does Java support inline function?

No, Java does not provide inline functions it is typically done by the JVM at execution time.


2 Answers

Inlining of methods is performed by the JIT compiler, not javac.

Modern JIT compilers (including Hotspot) can often inline even non-final methods, "undoing" the optimisation appropriately if necessary. They're basically scarily clever.

In short: it entirely depends on the VM. In my opinion, you should make your methods final or not based on what produces the cleanest code rather than performance. I'm personally a fan of "design for inheritance or prohibit it" but that's a different discussion :)

like image 151
Jon Skeet Avatar answered Sep 22 '22 15:09

Jon Skeet


Interesting question, prompted me to look into it further. 2 interesting remarks I found -

  • 1 comment that automatic inlining is a bug:

Contrary to the implication of many tips, methods declared as final cannot be safely inlined by the compiler, because the method could have a non-final declaration at runtime.

To see why, suppose the compiler looks at class A and subclass B, and sub-subclass C and sees a final method in A which it inlines into C. But then at runtime the versions loaded for A and B are different and the method is not final in A, and overridden in B. Then C uses the incorrectly inlined version. T

And, a bit more authoritatively, from a sun whitepaper, writing that methods can be left virtual,

Because the Java HotSpot VM can automatically inline the vast majority of virtual method invocations, this performance penalty is dramatically reduced, and in many cases, eliminated altogether.

Here's a more direct reference on the mechanism.

like image 45
Steve B. Avatar answered Sep 25 '22 15:09

Steve B.