What is the difference between atomic / volatile / synchronized?

You are specifically asking about how they internally work, so here you are: No synchronization private int counter; public int getNextUniqueIndex() { return counter++; } It basically reads value from memory, increments it and puts back to memory. This works in single thread but nowadays, in the era of multi-core, multi-CPU, multi-level caches it won’t … Read more

Why is volatile needed in C?

volatile tells the compiler not to optimize anything that has to do with the volatile variable. There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there’s … Read more

Difference between volatile and synchronized in Java

It’s important to understand that there are two aspects to thread safety. execution control, and memory visibility The first has to do with controlling when code executes (including the order in which instructions are executed) and whether it can execute concurrently, and the second to do with when the effects in memory of what has … Read more

Why is volatile not considered useful in multithreaded C or C++ programming?

The problem with volatile in a multithreaded context is that it doesn’t provide all the guarantees we need. It does have a few properties we need, but not all of them, so we can’t rely on volatile alone. However, the primitives we’d have to use for the remaining properties also provide the ones that volatile … Read more

When to use volatile with multi threading?

In C++11, don’t use volatile for threading, only for MMIO But TL:DR, it does “work” sort of like atomic with mo_relaxed on hardware with coherent caches (i.e. everything); it is sufficient to stop compilers keeping vars in registers. atomic doesn’t need memory barriers to create atomicity or inter-thread visibility, only to make the current thread … Read more