Is volatile required if the accessing thread is created by the same thread that previously assigned the variables?

StackOverflow https://stackoverflow.com/questions/20746211

Question

class MyClass {
    private int value;

    private void someFunction()
    {
        // value will never be assigned anywhere else while the thread is running
        this.value = 10;

        // start thread that reads value
    }
}

Does this requires a volatile or is the thread guaranteed to see the latest value?

Was it helpful?

Solution

Does this requires a volatile or is the thread guaranteed to see the latest value?

No, volatile is not required. That Java language definition says that the thread that is created will see all updates made by the creating thread before start() is called.

See Synchronization Order (JLS 17.4.4). To quote:

  • An action that starts a thread synchronizes-with the first action in the thread it starts.

Obviously, if the value is updated after the start() or if the new thread makes changes to the value that the starting thread needs to see then memory synchronization is needed.

The same holds true if you call thread.join(). Any updates made by thread that was joined with are seen by the caller after the join() returns.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top