15

When to use volatile keyword vs synchronization in multithreading?

Jyotirup
  • 2,882
  • 9
  • 30
  • 38

3 Answers3

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.

Ted Hopp
  • 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
  • @Gray - Okay. My "better example" is that `var` is of type `float`. – Ted Hopp Mar 28 '17 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.

kellyfj
  • 6,586
  • 12
  • 45
  • 66
Nrj
  • 6,723
  • 7
  • 46
  • 58
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.

erickson
  • 265,237
  • 58
  • 395
  • 493