radai radai - 29 days ago 12
Java Question

can moderm JVMs optimize different instances of the same class differently?

say I have 2 instances of the same class, but they behave differently (follow different code paths) based on a final boolean field set at construction time. so something like:

public class Foo {
private final boolean flag;

public Foo(boolean flagValue) {
this.flag = flagValue;
}

public void f() {
if (flag) {
doSomething();
} else {
doSomethingElse();
}
}
}


2 instances of
Foo
with different values for
flag
could in theory be backed by 2 different assemblies, thereby eliminating the cost of the if (sorry for the contrived example, its the simplest one I could come up with).

so my question is - do any JVMs actually do this? or is a single class always backed by a single assembly?

Answer

Yes, JVMs do this form of optimization. In your case, this would be a result of inlining and adaptive optimization for being a value to always be true. Consider the following code:

Foo foo = new Foo(true);
foo.f();

It is trivial to prove for HotSpot that Foo is always an actual instance of Foo at the call site of f what allows the VM to simply copy-paste the code of the method, thus eliminating the virtual dispatch. After inlining, the example is reduced to:

Foo foo = new Foo(true);
if (foo.flag) {
  doSomething();
} else {
  doSomethingElse();
}

This again, allows to reduce the code to:

Foo foo = new Foo(true);
foo.doSomething();

If the optimization can be applied does therefore depend on the monomorphism of the call site of foo and the stability of flag at this call site. (The VM profiles your methods for such patterns.) The less the VM is able to predict the outcome of your program, the less optimization is applied.

If the example was so trivial as the above code, the JIT would probably also erase the object allocation and simply call doSomething. There is a great tool named JITWatch that allows you to look into how your code gets optimized.