If multiple threads read a primitive type that has been previously set and does not change ever after, can they get a wrong value?
For example, assume the following simple code excerpt:
public static final boolean proceed = read(); // Read the value from a file
public static void doSomething() // Method accessed by multiple threads
{
if (proceed)
{
System.out.println("TRUE");
}
else
{
System.out.println("FALSE");
}
}
Assuming that the proceed
variable is initialized to true
, is it possible that, in one or more of the multiple threads that simultaneously run the doSomething()
method, the printed message is FALSE
?
If the proceed
variable was mutable, surely that would be possible, hence the need for synchronization, or for using an AtomicBoolean
(e.g., as per this question). But in this case proceed
is immutable and only set once, during the static initialization of the containing class.
Similarly for other primitive types, if a value is set as final, it should always be thread-safe to access it afterwards, correct?