Illustrates JAVA Memory Model (JMM: JAVA Memory Model)

introduction

This article illustrates two questions: What is the meaning of existence JMM? What is the inner workings of the JMM (highlight some data in concurrent programming mode access consistency).

1. Why use JMM?

When we first came into contact with JAVA language, they will be told JAVA program can run cross-platform (ie, the same code resources can be run in different hardware configurations, different operating system). JAVA is the case then how differences in different hardware and operating system memory access, to achieve the same result in a Java program running under various platforms are the same (to achieve results consistent access memory) it . It relies on the magic of the JMM.

Here to remember two facts:

(1) each of the lines of code written in fact we usually issued by a computer operating instructions, these instructions are run space CPU.

(2) a program will inevitably involve reading and writing variables and temporary data. These variables and data are stored in the temporary memory in the physical memory.

And there is a very significant speed between CPU and memory mismatch:

CPU execution speed quickly, and from the process memory to read data and write data to memory with the speed of the CPU to execute instructions compared to several orders of magnitude worse, so if you ever go through the operation of the data and to interact with memory carried out, it will greatly reduce the rate of instruction execution.

To solve this contradiction, people between the CPU and memory to increase the cache cache, as shown below:

Increase the cache, the execution of the program becomes:

(1) The operation requires data from the CPU to the main memory copy of the cache which

(2) CPU can read directly from the cache when it is calculated and write data thereto

(3) After the end of the operation, then the data cache to the main memory to refresh them.

In fact, it may be open simultaneously on multiple CPU threads, multiple threads access the same data, it is prone to the problem of data access inconsistent. How to ensure the consistency of data access is the key to solve the problems we JMM.

2.JMM inner workings

 

java jvm memory models and memory models are not the same, to separate area. As shown above, a plurality of threads using shared variables no direct locking manner, wherein

(1)实际内存(也叫主内存)中存储的是待共享的变量值。

(2)CPU中每个线程可以保留共享变量的副本。其中保存共享副本的地方称为每一个线程的工作内存threadLocal。每一个线程只能直接操作对应工作内存中的变量。

而不同线程之间的变量值传递则需要通过主内存(memory)来完成。如何保证主内存和线程工作内存的数据一致性,是我们需要重点关注的地方:

事实上,JMM中使用volatile关键字保证主内存和线程工作内存的数据一致性.

其工作原理大致如下:

(1)线程A的工作内存中的变量一旦发生了变化,就会有监视器检测到该变化。

(2)检测器通知CPU将该变化值刷新到内存。

(3)其他线程B/C..,在使用同一个变量时,为保证访问到的数据确实是线程A修改过的新数据,其采用的是CAS乐观锁策略(简单理解就是,永远以主存中的内容为参考)。即,

  1)拿自己工作内存中的变量值和主存中的变量值比较

  2)如果相等,则使用工作内存threadLocal里的变量

  3)如果不相等,则用主内存的变量替换本地的变量

而JMM的性能问题,则是通过指令重排的方式保证。

 

Guess you like

Origin www.cnblogs.com/dxtlearningblockchain/p/11110951.html