[concurrency-interest] Volatile/final and the JIT

Peter Veentjer alarmnummer at gmail.com
Tue May 5 07:02:45 EDT 2009


I have a question about the JIT and optimisations.

Is the JIT able to remove conditions based on volatile fields?

e.g.

class FooStatistics{.....}

class Foo{

   private final FooStatistics statisics;

   public Foo(FooStatistics statistics){
       this.statistics = statistics
   }

   void foo(){
      ... some logic

      if(statistics!=null)
           statistics.incSomeCasCounter();
   }

}

If I create a Foo with a null as statistics, the statistics part is
completely removed and my foo method is transformed to:

void foo(){
    ..... some logic
}

The problem is that you can't activate/deactivate statistics on an
existing object. So you could create something like this:

class Foo{

   private volatile FooStatistics statisics;

   public Foo(FooStatistics statistics){
       this.statistics = statistics
   }

   public void setStatistics(FooStatistics statistics){
      this.statistics = statistics;
   }

   void foo(){
      ... some logic

      if(statistics!=null)
           statistics.incSomeCasCounter();
   }

}

In this case I presume the JIT will have a very hard time removing the
statistics logic and as an additional cost, the system needs to access
an 'expensive' volatile variable.

I'm working on an STM implementation, and every read/write to
CAS/volatile variables counts..

So.. can anyone tell me if the final approach is the only way to go?
Or is the JIT able to do some magic like speculative removal of code..
and re-adding it if it is needed?

Peter


More information about the Concurrency-interest mailing list