• Post Reply Bookmark Topic Watch Topic
  • New Topic

Volatile Variables

 
abalfazl hossein
Ranch Hand
Posts: 635
  • Mark post as helpful
  • send pies
  • 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?
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • 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.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!