Are volatile variable ‘reads’ as fast as normal reads?

You should really check out this article: http://brooker.co.za/blog/2012/09/10/volatile.html. The blog article argues volatile reads can be a lot slower (also for x86) than non-volatile reads on x86. Test 1 is a parallel read and write to a non-volatile variable. There is no visibility mechanism and the results of the reads are potentially stale. Test 2 … Read more

What is the “volatile” keyword used for?

Consider this example: int i = 5; System.out.println(i); The compiler may optimize this to just print 5, like this: System.out.println(5); However, if there is another thread which can change i, this is the wrong behaviour. If another thread changes i to be 6, the optimized version will still print 5. The volatile keyword prevents such … Read more

Simplest and understandable example of volatile keyword in Java

Volatile –> Guarantees visibility and NOT atomicity Synchronization (Locking) –> Guarantees visibility and atomicity (if done properly) Volatile is not a substitute for synchronization Use volatile only when you are updating the reference and not performing some other operations on it. Example: volatile int i = 0; public void incrementI(){ i++; } will not be … Read more

Why does std::cout convert volatile pointers to bool?

ostream::operator<< has the following overloads, among others: ostream& operator<< (bool val ); ostream& operator<< (const void* val ); When you pass in a volatile pointer, the second overload can’t apply because volatile pointers cannot be converted to non-volatile without an explicit cast. However, any pointer can be converted to bool, so the first overload is … Read more