Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - static & volatile necessary when not instantiating objects?

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?

like image 321
spacecoyote Avatar asked Apr 12 '26 05:04

spacecoyote


1 Answers

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.

like image 147
Alex Suo Avatar answered Apr 13 '26 18:04

Alex Suo