javaoptimizationjvmnull-check

Java Null check elimination can cause bad code?


Recently, I read here about JVM optimizations , which are great,
but i have a problem with one optimization, namely Null Check Elimination (or Uncommon trap)

To sum up Null Check Elimination removes a if (obj == null) ... and hopes for the best, while if encounters a Segmentation Fault it recompiles the code and this time includes the neglected if (obj == null) ....

My question is, Given:

bool foo(MyClass obj)
{
   if(obj == null)
      return false;
   m_someVar++;
   obj.doSomething(m_someVar);
}

because the Null-Check is eliminated, and required only after m_someVar++.
will foo execute m_someVar++ an extra time when c will be null?

Edit:

Is there some source for deeper explanation on the implementation of this optimizations, which explain how does this optimization keeps the code semantically same?

Thanks


Solution

  • There are many possibilities ho to avoid the problem: Delaying or undoing the increment was already mentioned in a comment. The JVM has a big bag of tricks and some of them applies:


    (*) A null check may look like obj.getClass() which in assembler is a single instruction loading from a fixed offset relative to the obj pointer. When obj == null then an unmapped page ist hit.