When to use volatile keyword vs synchronization in multithreading?
-
http://stackoverflow.com/questions/3214938/java-volatile-modifier-and-synchronized-blocks and a quick goggling will show a lot of information – Umesh Awasthi Jan 02 '12 at 07:10
-
duplicate? https://stackoverflow.com/questions/9851133/ – Yousha Aleayoub Sep 24 '17 at 00:58
3 Answers
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.

- 232,168
- 48
- 399
- 521
-
`AtomicLong` handles the `var++` with a method and just a `volatile` field. Can you edit your answer to provide a better example? – Gray Mar 28 '17 at 16:58
-
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.
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.

- 265,237
- 58
- 395
- 493