15

When to use volatile keyword vs synchronization in multithreading?

2

3 Answers 3

27

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.

2
  • 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, 2017 at 16:58
  • @Gray - Okay. My "better example" is that var is of type float.
    – Ted Hopp
    Mar 28, 2017 at 17:58
10

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.

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.