Java – does creating a new thread have the side effect of refreshing the cache?

I wonder if creating a new thread in Java will trigger a cache refresh Suppose I do this in the following order:

>The thread runs and sets the variable x. > the thread creates a new thread. > New thread access X

My question is: is the new thread guaranteed to see the update of X made by the old thread in step 1 when it is created or when it starts execution? I know that if the old thread changes the value of X in the future, there is no guarantee that the new thread will see these changes No problem. I just want to know if the new thread will see the correct value at startup without explicit synchronization

When I first decided to investigate this topic, I thought a simple Google search would show the answer immediately, but for some reason, I couldn't find any results to solve this problem

Solution

yes.

In Java, there is a 'before - before' relationship, which specifies the visible memory effect between two actions If "a occurs before B", action B ensures that all changes completed by action a are seen

Starting a thread creates a "happen before" relationship between the "thread. Start()" call and all code executed on the new thread Therefore, ensure that the new thread sees the memory effect of changing variable x on the first thread

For a quick overview of the relationships that occurred before, see Java util. Memory visibility section of concurrent package overview In your case, the interesting bits are:

>Each operation in the thread occurs before each operation in the thread, which will appear in subsequent commands of the program. > A call to thread startup occurs before any operation in the thread is started

If you are curious, you can use more links:

>The JAVA memory model is described in Chapter 17 of the Java language specification > java memory model FAQ > everything else about JMM

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>