• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

volatile variable is used

 
hao li
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I got an information from a book that We had better do not use volatile variable.
but it seems It is right place to use it.
Please see my code.
variable connectStatus is private static volatile byte .
in method getDatabase we try to get a remote databse for the client, I have code:
if (connectStatus == DISCONNETED){
throw new IOException("Server is stopped!");
}
return new RemoteServerImpl.....
I have A gui with stop server button. the first row of method actionPerformed in the button ActionListener is:
connectStatus = DISCONNETED;
What do you think about it?
Do you think I am right?
 
Pete Lyons
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The volatile keyword is a signal to compilers that a variable may be altered by other code (relationships that are had to detect at compile time, other theads, as well as introspection), and thus should be checked every time. Often, a Thread might make a local copy of some int inside a while loop as an optimization, and this copy could become inaccurate. With the volatile keyword, the actual value will be re-read each time to protect against this.
I'm almost certain you don't need it for your if statement.
 
Max Habibi
town drunk
( and author)
Sheriff
Posts: 4118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pete is correct, don't use it. Almost no operating system that I know of implements it correctly anyway.
HTH,
M, author
The Sun Certified Java Developer Exam with J2SE 1.4
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic