I want to know whether creating a new thread in Java triggers a cache flush. Suppose I do something like this, in this sequence:
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.
Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables. Operations like increment and decrement are composite operations.
In Java, threads doesn't cache any object or variable, they just have a reference to an instance of an object. Talking about thread cache memory is more like talking about operative systems threads...
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With