From docs:
Using volatile variables reduces the risk of memory consistency errors
But this means that sometimes volatile variables don’t work correct?
Strange how it can be used – for my opinion it is very bad code that sometimes work sometimes not. I tried to Google but didn’t find example memory consistency error with volatile. Could you please propose one?
The issue is not so much that
volatileworks unreliably. It always works the way it is supposed to work. The problem is that the way it is supposed to work is sometimes not adequate for concurrency control. If you usevolatilein the wrong situation, you can still get memory consistency errors.A
volatilevariable will always have any writes propagated to all threads. However, suppose you need to increment the variable among various threads. Doing this(*):There is a chance that counter increments will be missed. This is because the value of
mCounterneeds to be first read by each thread before a new value can be written. In between those two steps, another thread may have changed the value ofmCounter. In situations like this, you would need to rely onsynchronizedblocks rather thanvolatileto ensure data integrity.For more info on
volatilevs.synchronized, I recommend the article Managing volatility by Brian Goetz(*) I realize that the above would be better implemented with
AtomicInteger; it’s a contrived example to illustrate a point.