Search code examples
javathread-safetyprimitive

Multiple threads reading a primitive type


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?


Solution

  • The fact that your variable is final guarantees that all threads will see it in a consistent post-initialisation state. This is applicable to objects' references too (i.e. all threads will see a non null value of the Object if it has been initialised to a non null reference - but if your object is not thread-safe, some threads might see the object itself in an inconsistent or stale state).

    ps: that is assuming your read method does not try to read the boolean value in which case it would see the default (false) value.