• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can Static Variables have multiple copies when in a multi threaded environment and under heavy load?

 
Prafull Prashant
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am writing a code which runs in a mult- threaded environment.

I have declared a static variable which is globally visible across the application. Each thread landing on a piece of code has the capability to change the value of my static variable.

My question is, under heavy load condition, is it possible that at the same time two different threads may have different values of the static variable (assuming at the time two threads are looking up there is no change in value of that variable by other threads).

The question arose when someone pointed me that at runtime JVM optimizes the static variable references by caching it in locally and can lead to multiple values of same variable. Hence, its never use static variable, instead use volatile variable.

Is this true? Please let me know if i was able to describe my problem properly
 
Kaustav Ganguly
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it is required to make the variable volatile to make it thread safe.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!