I want to know whether creating a new thread in Java triggers a cache flush. Suppose I do something like this, in this sequence:
- A thread runs and sets a variable X.
- The thread creates a new thread.
- The new thread accesses X.
My question is this: is the new thread, either at the time it is created or at the time it begins execution, guaranteed to see the update made to X by the old thread in step 1? I understand that if the old thread changes the value of X in the future, it is not guaranteed that the new thread will see these changes. That’s fine. I just want to know whether the new thread will see the right values when it starts without need for explicit synchronization.
When I first decided to look into this topic, I thought a simple google search would immediately reveal the answer, but for some reason, I can’t find any result that addresses this question.
Yes, it is.
In java, there is ‘happens-before’ relation that specifies what memory effects are visible between two actions. If “A happens-before B”, then action B is guaranteed to see all changes done by action A.
Starting a thread creates ‘happens-before’ relation between “thread.start()” call and all code that executes on new thread. New thread is therefore guaranteed to see memory effect of changing variable X on first thread.
For quick overview of happens-before relation, see Memory Visibility part of java.util.concurrent package overview. In your case, interesting bits are:
More links if you are curious: