Forums Register Login

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

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
Yes, it is required to make the variable volatile to make it thread safe.
It runs on an internal combustion engine. This ad does not:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1932 times.
Similar Threads
Need to understand about threading issues?
Multiple Home & env. entities
volatile and static keywords
Threads 002
How do you execute new code in an existing Thread?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 06:02:16.