This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Volatile Fields  RSS feed

 
Saurabh Saha
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
please tell me what is volatile field and were we use this field.

Thanks & Regards,
Vivek Mishra
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java will often fetch once from its memory location the value of a variable that is used several times and not store it in its original location until several statements later.

float p = 5.f;
p = p + q;
if ( p > 10.f ) p = (float)Math.sqrt( p );

However, if there is a another thread, or even a system process, that either needs the very latest value of p or may change p while this thread is active, we must to instruct Java to always fetch p from its memory location each time it is used and to always save p in its memory location as soon as it is changed.

So we say:
volatile float p = 5.f;

[ December 25, 2004: Message edited by: Mike Gershman ]
[ December 25, 2004: Message edited by: Mike Gershman ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!