Java Memory Model

The Java Memory Model stipulates that all variables are stored in the main memory; the working memory of a thread stores a copy of the main memory of the variables used by the thread; all operations (reading, assignment, etc.) of a thread on variables must be carried out in the working memory, rather than directly reading and writing variables in the main memory.

Different threads cannot directly access the variables in each other's working memory. The transfer of variable values between threads needs to be completed through the main memory. The interactive relationship among thread, main memory and working memory is shown in the figure:

The main memory and working memory mentioned here are not at the same level as the Java heap, stack, method area, etc. in the commonly mentioned JAVA memory area. The two are basically irrelevant. If the two must barely correspond, from the definition of variables, main memory and working memory, the main memory mainly corresponds to the object instance data part in the Java heap, while the working memory corresponds to some areas in the virtual machine stack.

As for the specific interaction protocol between main memory and working memory, that is, how to copy a variable from main memory to working memory and how to synchronize it back to main memory, the following eight operations are defined in the JAVA memory model. During the implementation of virtual machine, each of the following operations must be atomic and inseparable.

These eight operations are roughly as follows:

If you want to copy a variable from main memory to working memory, you should perform read and load operations in sequence. If you want to synchronize variables from working memory back to main memory, you should perform store and write operations in sequence. Note that the JAVA memory model only requires that the above two operations must be executed in sequence, and there is no guarantee that they will be executed continuously. In other words, other instructions can be inserted between read and load and between store and write. For example, when accessing variables A and B in main memory, one possible order is read a, read B, load B and load a. In addition, the JAVA memory model also stipulates that the following rules must be met when performing the above eight basic operations:

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
分享
二维码
< <上一篇
下一篇>>