Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile confusion

 
Ja vardhan
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends,
I didnt understood what volatile is all about...I have searched this forum and gone through some of the threads, still not cleared.

I read the below from one thread-
To declare that a variable can be modified asynchronously by concurrent threads - use 'volatile'.

what does it mean>>>

Pls clarify.

Thanks in advance.
 
Amol Fuke
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.
 
Ja vardhan
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amol,
Thanks for your early reply. I got some idea with your words, but still not clear; what I am thinking is- if we are not going to use 'synchronized' then mutiple threads can access our variable at a time.

If I want to restrict the variable in such a way that multiple threads should not access concurently then I will go with 'synchronized' keyword.
If I want to allow multiple threads concurently, simply I will forget about synchronization (forgive me if I am wrong).

Then whats the special use of 'volatile' here???

Thank you once again.
 
vipul patel
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Volatile:

A class-member variable might be shared between multiple threads. So each thread maintains its own working copy of this variable. now if the variable is not volatile, each thread will NOT reconcile its working copy with the master copy at object level. so just put volatile infront of all those variable which are shared among multiple threads. it will force all threads to reconcile their own copies of variable to master copy.

However volatile is not frequently used thing in java. better way to use synchronization.
 
Ja vardhan
Ranch Hand
Posts: 169
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Much Thanks Dilip. I got clear idea what volatile is for.

Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic