Is the public static final int thread safe?

I want to have a file with constant available constants from multiple threads. Is there a class-safe implementation with a lot public static final int

to do this?

+3


source to share


4 answers


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 .

+8


source


Yes, it's safe.

The value never changes, so there is no risk of race conditions. Java guarantees that the value is initialized before anything tries to use it.



Whether this is a better architecture for other reasons (design clarity, etc.) is another question.

+3


source


Yes, 100% safe. It is final, so no one can change it. Each stream should have reader-only access and there are no read-only assertions.

+3


source


For primitives, making them final

compile time constants (if they are initialized directly, not as a result of a method), and int

are primitive. Thus, final int

it makes it immutable and therefore thread-safe.

+1


source







All Articles