Can Static Variables have multiple copies when in a multi threaded environment and under heavy load?
Joined: Jan 15, 2010
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
Joined: Dec 14, 2009
Yes, it is required to make the variable volatile to make it thread safe.