Volatile Vs Atomic [duplicate]

The effect of the volatile keyword is approximately that each individual read or write operation on that variable is made atomically visible to all threads. Notably, however, an operation that requires more than one read/write — such as i++, which is equivalent to i = i + 1, which does one read and one write … Read more

Does Interlocked.CompareExchange use a memory barrier?

Any x86 instruction that has lock prefix has full memory barrier. As shown Abel’s answer, Interlocked* APIs and CompareExchanges use lock-prefixed instruction such as lock cmpxchg. So, it implies memory fence. Yes, Interlocked.CompareExchange uses a memory barrier. Why? Because x86 processors did so. From Intel’s Volume 3A: System Programming Guide Part 1, Section 7.1.2.2: For … Read more

Volatile variable in Java

Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to “main memory”. Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself. Just for your reference, When is volatile needed ? When multiple threads … Read more

How to stop / freeze / pause volatile RAND / RANDBETWEEN / RANDARRAY?

first, let’s see what says the fox =WHATTHEFOXSAY() is a unique easter egg google sheets function (discovered by @kishkin) that randomly generates a pre-set string of text on user demand which is a huge deal because while the generation is random, the recalculation is not affected by onEdit, onChange nor onOpen events, so with some … Read more

Volatile in C++11

Whether it is optimized out depends entirely on compilers and what they choose to optimize away. The C++98/03 memory model does not recognize the possibility that x could change between the setting of it and the retrieval of the value. The C++11 memory model does recognize that x could be changed. However, it doesn’t care. … Read more

Happens-before relationships with volatile fields and synchronized blocks in Java – and their impact on non-volatile variables?

Yes, it is guaranteed that thread 2 will print “done” . Of course, that is if the write to b in Thread 1 actually happens before the read from b in Thread 2, rather than happening at the same time, or earlier! The heart of the reasoning here is the happens-before relationship. Multithreaded program executions … Read more

Is volatile expensive?

On Intel an un-contended volatile read is quite cheap. If we consider the following simple case: public static long l; public static void run() { if (l == -1) System.exit(-1); if (l == -2) System.exit(-1); } Using Java 7’s ability to print assembly code the run method looks something like: # {method} ‘run2’ ‘()V’ in … Read more