How to declare array elements volatile in Java?

Use AtomicIntegerArray or AtomicLongArray or AtomicReferenceArray The AtomicIntegerArray class implements an int array whose individual fields can be accessed with volatile semantics, via the class’s get() and set() methods. Calling arr.set(x, y) from one thread will then guarantee that another thread calling arr.get(x) will read the value y (until another value is read to position … Read more

Is it allowed for a compiler to optimize away a local volatile variable?

No. Access to volatile objects is considered observable behavior, exactly as I/O, with no particular distinction between locals and globals. The least requirements on a conforming implementation are: Access to volatile objects are evaluated strictly according to the rules of the abstract machine. […] These collectively are referred to as the observable behavior of the … Read more

C# volatile variable: Memory fences VS. caching

I’ll address the last question first. Microsoft’s .NET implementation has release semantics on writes1. It’s not C# per se, so the same program, no matter the language, in a different implementation can have weak non-volatile writes. The visibility of side-effects is regarding multiple threads. Forget about CPUs, cores and caches. Imagine, instead, that each thread … Read more

Why is volatile deprecated in C++20?

There’s a good talk by the C++ committee language evolution chair on why. Brief summary, the places that volatile is being removed from didn’t have any well defined meaning in the standard and just caused confusion. Motivating (Ambiguous) Examples Volatile bit Fields should be specified by your hardware manual and/or compiler. Is += a single/atomic … Read more

Difference between Interlocked.Exchange and Volatile.Write?

the Interlocked.Exchange uses a processor instruction that guarantees an atomic operation. The Volatile.Write does the same but it also includes a memory barrier operation. I think Microsoft added Volatile.Write on DotNet 4.5 due to support of ARM processors on Windows 8. Intel and ARM processors differs on memory operation reordering. On Intel, you have a … Read more