I have a class ContainerClass that has some static variables. Several simultaneously running threads access these static variables and they always need to have the most recent value.
The threads access the variables without an object of the ContainerClass, but instead like
ContainerClass.variable_A;
Do I still need to declare the variables that are shared between the threads volatile in ContainerClass? Does any caching happen in the threads?
EDIT: Edited for some clarity.
EDIT2: For more clarity: Multiple threads read the values of these volatile variables, but only one thread sets them. Will the reading-threads cache the variable or always have the up-to-date version, since there's no object instantiation in the reading threads?
Quick answer is Yes. Static is a instance/class modifier. It has nothing to do with synchronization and memory model. While volatile ensures 1) instruction optimization doesn't swap the operation to volatile variable to anything before/after that 2)anything happens before manipulating the volatile variable are written to main memory. So yes you do need to make it volatile.
Having said all the above I personally think your design isn't good. Exposing such global static volatile basically violates encapsulation. Unless you have such a performance reason to do so (which I guess not), the static var better be private member and latest value returned by methods to have better encapsulation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With