Search code examples
c#javamultithreadingmemory-optimization

What are the differences between the volatile in c# and java?


In some .net documentation I have read this is how the compiler handles volatile:

  • *"Reading from a volatile or using the Thread.VolatileRead method is logically an acquire fence"
  • "Writing to a volatile or using the Thread.VolatileWrite method is logically a release fence" *

These fences apply at both complier and architecture level.

Of course the main difference in VC++ is that the fence is only applied at complier level.

So my question is, what are the memory reordering prevention semantics of volatile in Java?

Conversion:

Fence = Barrier Barrier = Fence

References:

Joe Duffy (Concurrent Programming on Windows)


Solution

  • In Java, the javac compiler does next to nothing with volatile. It doesn't re-order statements and does almost no optimisation.

    The JIT on the other hand can do quite a bit of optimisation and re-ordering.

    The important features of volatile are;

    • read/write access cannot be optimise away
    • any write which occurs before a volatile write has to occur before the write.
    • any read which occurs after a volatile read, must occur after the read.