Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use volatile vs synchronization in multithreading in java?

When to use volatile keyword vs synchronization in multithreading?

like image 442
Jyotirup Avatar asked Jan 02 '12 07:01

Jyotirup


People also ask

What is the use of volatile and synchronized?

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.

Do we need volatile with synchronized?

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 should I use volatile in java?

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.

What is difference between volatile atomic classes and synchronization and in what scenarios will you use each of them?

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.


1 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.

like image 98
Ted Hopp Avatar answered Sep 19 '22 21:09

Ted Hopp