[5] Java Memory Model (JMM)

Java Memory Model (JAVA memory model) describes how threads interact through memory. Specifically, there is a main memory area (Main Memory or Java Heap Memory) in the JVM, which is shared by all threads, and each thread has its own working memory (Working Memory), which is stored in the main memory. For the copy of some variables, the thread's operations on all variables do not occur in the main memory area, but in the working memory, and the threads cannot directly access each other. The transmission of variables in the program is completed by the main memory. of.

 

The efficiency and consistency of the hardware:

Although the CPU cache solves the efficiency problem, it will bring a new problem: data consistency (visibility, which will be explained in the next article).

When the program is running, the data needed for running will be copied to the CPU cache, and the CPU will no longer deal with the main memory when performing operations.

Instead, read and write data directly from the cache, and only flush the data to the main memory when the operation is over

Main memory and working memory:

 

The main goal of the Java Memory Model (JMM) is to define the access rules of each variable in the program, that is, the low-level details of storing variables in memory and removing variables from memory in the JVM

E.g:

The thread fetches data from the heap and stores the data in the lower level details of the heap.

The concept of pointing variables in the stack to the data in the heap and performing operations is a refined model.

 

Synchronization of working memory and main memory:

When the thread ends, the data in its corresponding working memory will be flushed to the main memory.

In fact, the JVM has been optimized for the current hardware level to a large extent, which basically guarantees the timely synchronization of the working memory and the main memory to a large extent , which is equivalent to using volatile by default. But only to the maximum ! When the CPU resources are always occupied, the synchronization between the working memory and the main memory, that is, the visibility of variables will not be so timely!

Two provisions of JMM on synchronized (lock):

1. Before the thread is unlocked, the latest value of the shared variable must be flushed to the main memory

2. When the thread is locked, the value of the shared variable in the working memory will be cleared, so when using the shared variable, the latest value must be re-read from the main memory.

sysout, sleep and other operations that release the cpu (input and output will release the cpu) can refresh the data in the work area to the main memory.

Guess you like

Origin blog.csdn.net/Jack_PJ/article/details/87981177