Why does volatile exist?

volatile is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially … Read more

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