Search code examples
c#javamultithreadingvolatile

Java seems to support volatile fields of type long, while C# does not - What are the reasons behind this?


Can anyone explain to me what the benefits and and drawbacks of the two different approaches are?


Solution

  • When a double or long in Java is volatile, §17.7 of the Java Language Specification requires that they are read and written atomically. When they are not volatile, they can be written in multiple operations. This can result, for example, in the upper 32 bits of a long containing a new value, while the lower 32 bits still contain the old value.

    Atomic reads and writes are easier for a programmer to reason about and write correct code with. However, support for atomic operations might impose a burden on VM implementers in some environments.