Sun Java Solaris Communities My SDN Account Join SDN
 
Article

The Java HotSpot Performance Engine: Method Inlining Example

 
 

Articles Index


 
 class A {
 final int foo() { return 3; }
 }
 

Given this class, any call to foo() can be replaced with the constant "3". Any Java1 virtual machine can do this, because the "final" keyword explicitly dictates that it isn't possible to have a subclass that overrides "int foo()".

Inlining the method provides the following benefits at the call site:

  • No method call
  • No dynamic dispatch
  • Possible to constant-fold the value, eg. "a.foo()+2" becomes 5 with no code executed at runtime.

In the past, programmers often inserted the "final" keyword for exactly this reason. Or to better facilitate inlining and increase execution speed, they would combine many smaller methods into one larger method. But in many ways, such techniques defeat the entire facility of modularization and reusability built into the programming language.

Unlike traditional virtual machines, the Java HotSpot VM is able to inline the class without the "final" keyword:

class B {
int foo() { return 3; }
 }
 

As long as there are no subclasses that override "int foo()", everything is fine. But a problem arises when dynamic class loading is used to load a class such as C:

 
class C extends B {
int foo() { return 6; }
  }
  

Now, any code that inlined calls to B.foo() has to be recompiled, because a variable in the code of type B can point to objects of either class B or C. The code that's generated can't know whether it's going to be an object of class B or C until runtime.

Until class C was loaded, there was no problem, because there was only one class (and method foo) that could be pointed to by a variable of type B. But once you load class C, that's no longer true.

Such problem areas are detected by recording for every compilation, all of the assumptions that the code makes. On every class load, all these assumptions are checked and, if violated, the now-incorrect compiled code is retired (deoptimized).

Return to main article

_______
1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.