When to use volatile keyword vs synchronization in multithreading?
Marking a variable as volatile basically tells all threads to do read and write operations on main memory only. synchronized tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.
You can do synchronization without using synchronized block. It's not a necessary to use volatile variable in it... volatile updates the one variable from main memory..and synchronized Update all shared variables that have been accessed from main memory.. So you can use it according to your requirement..
When to use it? You can use a volatile variable if you want to read and write long and double variable automatically. It can be used as an alternative way of achieving synchronization in Java. All reader threads will see the updated value of the volatile variable after completing the write operation.
Volatile and Atomic is apply only on variable , While Synchronized apply on method. Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With