Ok so I just read this question Do you ever use the volatile keyword in Java?, and I get using a volatile variable in order to stop a loop. Also I\'ve seen this reference, h
No, reading a volatile
variable is faster than than reading an non-volatile
variable in a synchronized
block.
A synchronized
block clears the cached values on entry which is the same as reading a volatile
variable. But, it also flushes any cached writes to main memory when the synchronized block is exited, which isn't necessary when reading volatile
variable.
There's a numebr of things wrong in your question: You can do a reliable read-update-write with volatile
so long as you use Atomic*FieldUpdater
and a cas-loop. Volatiles can be "cached", they just need to obey the relevant happens-before semantics specified.
Synchronisation typically involves obtaining a lock, which is relatively expensive (although may actually be quite cheap). Simple concurrent optimisations may use non-naive implementation techniques.