Is there a side effect of clearing the cache when creating a new thread?

I want to know if creating a new thread in Java triggers a cache flash. Suppose I do something similar in this sequence:

  • The thread starts and sets the variable X.
  • A stream is created in the stream.
  • The new thread accesses X.

My question is this: is this a new thread, either at the time of its creation or at the time of its launch, guaranteed to view the update made by X on the old thread in step 1? I understand that if the old thread changes the value of X in the future, it will not guarantee that the new thread will see these changes. It's great. I just want to know if the new thread will see the correct values ​​when it starts without the need for explicit synchronization.

When I first decided to study this topic, I thought that a simple Google search would immediately open the answer, but for some reason I can’t find a result that solves this issue.

+6
source share
1 answer

Yes it is.

In java, there is a “happen before” relationship that indicates which memory effects are visible between two actions. If "A occurs before B", then action B is guaranteed to see all the changes made by action A.

Starting a thread creates a "happen-to" relationship between the call to "thread.start ()" and all the code that runs in the new thread. Thus, the new thread is guaranteed to see the memory effect when changing the variable X in the first thread.

For a brief overview of the “wait” relationships, see “Memory Visibility” in the java.util.concurrent package overview. In your case, the interesting bits are:

  • Each action in the thread occurs - before each action in this thread, which comes later in the order the program runs.
  • A call is launched to start in the thread - before any action in the running thread.

Additional links if you are interested:

+9
source

Source: https://habr.com/ru/post/903798/


All Articles