Is the public static final int thread safe?
Yes, it is thread-safe. Any variable static final
must be initialized after class initialization. Thus, once a class containing such a variable static final
is used anywhere in your code, it is always fully initialized (i.e. set to a value) by the JVMs requirement .
With the primitive, int
this condition is even more stringent. A primitive variable static final
(the same applies to String
) is a so called compilation constant that is built into the java java compiler. The only requirement is that the value can be computed by the Java compiler, that is, it must not be the result of a non-constant evaluation. Since you write that you want to define constants, I assume this is not the case for your use case. So these constant values ββare directly copied to their access location, which reduces the corner case of safety without the threads of the variable static final
being modified by reflection, which is hypothetically a problem with non-primitive types.
Also, it is a good idea to use such variables as it avoids the use of so-called magic numbers .
source to share