Ok, I believe that if some_local_variable reads as 0 (due to writing to v ), i will be considered as 42.
The hard part is "at some later point in time." While volatility is usually discussed in terms of flushing, it says that itβs not the way it is actually defined in the specification (either Java or C #).
From the C # 4 language specification, section 10.5.3:
For non-volatile fields, optimization methods that change the order of instructions can lead to unpredictable and unpredictable results in multithreaded programs that access fields without synchronization, for example, provided by the lock operator (Β§8.12). These optimizations can be performed by a compiler, a runtime system, or hardware. For volatile fields, such reordering optimizations are limited:
- Reading a volatile field is called volatile reading. Intermittent reading has "acquire semantics"; that is, it is guaranteed to occur before any memory references that occur after it in a sequence of commands.
- A variable field record is called volatile write. A volatile entry has "release semantics"; that is, it is guaranteed to happen after any memory references before a write command in a sequence of commands.
Here is an example that is very similar to yours, but depends on the value read from the mutable variable.
And, like Eric, I would not rely heavily on volatility. It's hard to reason, and it's best to leave Joe Duffy / Stephen Tus in the world.
source share