[concurrency-interest] Volatile/final and the JIT

Christian Vest Hansen karmazilla at gmail.com
Tue May 5 09:17:21 EDT 2009


On Tue, May 5, 2009 at 1:02 PM, Peter Veentjer <alarmnummer at gmail.com> wrote:
> 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
> }

Different instances of this class may have different values assigned
to the statistics field, but the code itself is static and, I would
assume, optimized as such. Therefor, a JIT that eliminates that
condition would still have to be mindful of any future instances where
such an optimization is invalid.

>
> 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?

I believe that hotspot is able to do dynamic deoptimization of code
that is conditional on normal variables, but the visibility semantics
of a volatile read might prevent this from happening. That said,
volatile reads are "pretty cheap" and the CPU might be able to predict
the branch, though pretty much all I know about branch prediction is
the name.

>
> Peter
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at cs.oswego.edu
> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>



-- 
Venlig hilsen / Kind regards,
Christian Vest Hansen.



More information about the Concurrency-interest mailing list