• Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between static and volatile variables  RSS feed

 
chandana nannapaneni
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I studied that if we declare a variable as static, there will be only one copy of the variable.
So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).

If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.
So, the value of the variable in all the threads will be the same.

So, in both cases, the main point is that the value of the variable is same across all threads.

Then what is the difference between declaring a variable as static or volatile?

Please correct me if I am wrong.

Thanks.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey,

the volatile keyword is rarely used and pretty poorly documented too ...

essentially, the volatile keyword indicates that this variable, which can be static or non-static, is used and altered by different threads.
hence the variable is never cached thread locally, but always used directly from the main memory..

in addition the variable is synchronized on itself, just as if you used

 
Rob Spoor
Sheriff
Posts: 21117
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static and volatile have completely different purposes. Like Sebastian said, volatile is for multi threaded programs. An instance (non-static) variable can be volatile.

Sebastian, your synchronized example is actually quite bad. You will still need that synchronization with volatile variables - the volatile protects against assignment and reading of the value, not calling methods. So it's more like this:
is more ore less equivalent to this:
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
guess i got that concept a little wrong ...

thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!