When to use volatile keyword vs synchronization in multithreading?
volatile to guarantee that each read access to a variable will see the latest value written to that variable. Use
synchronized whenever you need values to be stable for multiple instructions. (Note that this does not necessarily mean multiple statements; the single statement:
var++; // NOT thread safe!
is not thread-safe even if
var is declared
volatile. You need to do this:
See here for a nice summary of this issue.