Reputation: 2920
When to use volatile keyword vs synchronization in multithreading?
Upvotes: 15
Views: 11073
Reputation: 6831
Volatile only ensures the read operation always gives the latest state from memory across threads. However, it does not ensure any write safety / ordering of operations, i.e. two threads can update the volatile variable in any random order. Also it does not ensure that multiple operations on the variable are atomic.
However a synchronized block ensures latest state and write safety. Also the access and update to variable is atomic inside a synchronized block. The above, however is true, only if all the access / updates to the variable in question are using the same lock object so that at no time multiple threads gets access to the variable.
Upvotes: 10
Reputation: 234795
Use 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:
synchronized(LOCK_OBJECT){var++;}
See here for a nice summary of this issue.
Upvotes: 27
Reputation: 269667
That's a pretty broad question. The best answer I can give is to use synchronized
when performing multiple actions that must be seen by other threads as occurring atomically—either all or none of the steps have occurred.
For a single action, volatile
may be sufficient; it acts as a memory barrier to ensure visibility of the change to other threads.
Upvotes: 3