NittinS February 2016

Volatile Keyword is of no use When using synchronized?

I was trying to understand the use of volatile keyword in java. I understand it will write the data in main memory not in thread cache.

But is that really useful. I am using multi threading and

shouldn't I be using synchronized cause I don't want dirty reads to other threads. so at what exact situation volatile can be useful and most important to use?

Please give some example.

Answers


Zbynek Vyskovsky - kvr000 February 2016

synchronized is much more expensive than plain volatile.

volatile is useful when you just need to read/write single variable and don't care about atomicity of complex structures.

synchronized is useful when you need to perform complex operations, update several variables or set one variable when compared another one and ensure the atomicity of such operation. Also it is used when doing higher level synchronization such as conditions, i.e. synchronized/wait/notify in java. But for that Lock/Condition can be used too.


shubham misra February 2016

For even better explanation about using volatile variables you can view the following link with JB Nizet's answer. It compliments well the answer posted by Zbynek and further explains the relation between volatile, atomic variables & complexity. Hope this helps.

Post Status

Asked in February 2016
Viewed 3,803 times
Voted 8
Answered 2 times

Search




Leave an answer