It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes volatile  confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "volatile  confusion" Watch "volatile  confusion" New topic

volatile confusion

Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
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

Joined: Apr 08, 2005
Posts: 129
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.

"There are no mistakes, only lessons"
Ja vardhan
Ranch Hand

Joined: May 09, 2005
Posts: 169
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

Joined: Oct 16, 2005
Posts: 146

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

Joined: May 09, 2005
Posts: 169
Much Thanks Dilip. I got clear idea what volatile is for.

Don't get me started about those stupid light bulbs.
subject: volatile confusion
jQuery in Action, 3rd edition