• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Volatile Variables

 
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

The volatile keyword was introduced to the language as a way around optimizing compilers. Take the following code for example:




An optimizing compiler might decide that the body of the if statement would never execute, and not even compile the code. If this class were accessed by multiple threads, flag could be set by another thread after it has been set in the previous code, but before it is tested in the if statement. Declaring variables with the volatile keyword tells the compiler not to optimize out sections of code by predicting the value of the variable at compile time.


http://www.ibm.com/developerworks/library/j-thread.html


Please explain more about this.
If flag is a volatile variable, Then why isn't used volatile keyword in code?
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

abalfazl hossein wrote:If flag is a volatile variable, Then why isn't used volatile keyword in code?


Because the author didn't do a good job of writing clearly. He's really talking about two different cases, but he's only showing the code once.

1. If "flag" is not declared as volatile, as shown, then the code marked "//this could happen" may execute, as explained in the article (even though that seems to make no logical sense to most people).

2. If "flag" is declared as volatile, (which is not shown here) then the code marked "//this could happen" can never happen. Volatile fixes the problem described in this section.
 
Ranch Hand
Posts: 443
3
Eclipse IDE C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think that article is very old 2001 ? and its definition of volatile is a bit out dated , I would look up JSR 133 and use that definition.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic