0

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?

Community
  • 1
  • 1
PNS
  • 19,295
  • 32
  • 96
  • 143

4 Answers4

1

Since proceed is static and final , it can not be reassigned which turns in to thread-safe.

static says it is class level and final says it's value can't be changed and this is a primitive so defiantly this immutable and hence thread-safe .

amicngh
  • 7,831
  • 3
  • 35
  • 54
1

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

You are saying it is immutable (static and final), so we can safely say it is thread-safe.

kosa
  • 65,990
  • 13
  • 130
  • 167
1

The reference is thread-safe because it's immutable.

If it were mutable, you would need to use the volatile keyword to make sure you get the latest value if modified in another thread.

Do you ever use the volatile keyword in Java?

Community
  • 1
  • 1
wrschneider
  • 17,913
  • 16
  • 96
  • 176
  • 1
    Although your comment on double and long is accurate, it does not apply to this question. The same question with a double instead of a boolean would get the same answer. – assylias Jul 18 '12 at 13:19