NittinS
NittinS

Reputation: 53

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.

Upvotes: 1

Views: 110

Answers (2)

shubham misra
shubham misra

Reputation: 31

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.

Upvotes: 0

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18825

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.

Upvotes: 2

Related Questions