🔧 Fix a Volatile Field Reordered Around a Non-Volatile Read
Marking a single field volatile only guarantees ordering and visibility for reads and writes of that one field — the JIT and the CPU are still free to reorder reads of other, non-volatile fields around it, so a common pattern of ‘check a volatile flag, then read a related non-volatile field’ doesn’t actually guarantee the non-volatile read sees the value that was written before the flag was set, on architectures with weaker memory ordering than x86.
🔎 The Problem
private volatile bool _ready;
private int _cachedResult; // NOT volatile
public void Producer()
{
_cachedResult = ComputeExpensive();
_ready = true; // volatile write
}
public int Consumer()
{
if (_ready) // volatile read
return _cachedResult; // NOT guaranteed to see the write above
return -1;
}
✅ Fix: Use a Real Memory Barrier, Not Just One Volatile Flag
- Replace the manual flag-and-field pattern with
Interlocked.CompareExchangeor a full fence viaThread.MemoryBarrier()around both the write and the read, which guarantees ordering for every field involved, not just the one marked volatile. - Where the value only needs to be published once and read many times, consider
Lazy<T>with thread-safety modeExecutionAndPublication, which handles the memory barrier correctly without hand-rolled flag logic. - If you specifically need a single reference published safely,
Volatile.Write/Volatile.Readon the reference itself (rather than a separate bool flag) ties the barrier directly to the value that matters.
🚨 Why This Is Dangerous
- This bug is effectively invisible on x86/x64 in normal testing because its strong memory model hides the reordering — it tends to surface only under real contention on ARM or in a stress test specifically designed to catch it.
Volatile orders one field’s reads and writes — it was never a promise about anything sitting next to it in memory.



