Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of Java memory model

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the knowledge points of Java memory model". In daily operation, I believe many people have doubts about what are the knowledge points of Java memory model. Xiaobian consulted all kinds of information and sorted out simple and easy to use operation methods. I hope to help you answer the doubts of "what are the knowledge points of Java memory model"! Next, please follow the small series to learn together!

For Java memory model, let's start with hardware memory model.

hardware memory model

Let's first look at the simple architecture of hardware memory, as shown in the following figure:

hardware memory structure

This is a simple hardware memory structure diagram, the real structure diagram is much more complex than this, especially in the cache layer, now the computer CPU cache generally has three layers, you can also open your computer to see, open the task resource manager---> performance--> cpu, as shown below:

CPU cache

As can be seen from the figure, the CPU of my machine has a three-level cache, a first-level cache (L1), a second-level cache (L2), and a third-level cache (L3). The first-level cache is closest to the CPU, and the third-level cache is closest to the memory. The data of each first-level cache is part of the next-level cache. The three-level cache architecture is shown below:

Now that we have some understanding of hardware memory architecture, let's figure out why we need to add cache between CPU and memory.

On this issue we simply say, we know that the CPU is high-speed, and memory is relatively low-speed, which will cause a problem, can not make full use of the characteristics of CPU high-speed, because the CPU needs to wait every time it gets data from memory, so it wastes the performance of CPU high-speed, cache is used to eliminate the gap between CPU and memory. Cache speed is greater than memory is less than CPU, after adding cache, CPU directly from the cache to read data, because cache is relatively fast, so it makes full use of the characteristics of CPU cache. But not every time you can read data from the cache, this is the same as the cache tools used in our project, such as redis, there is also a cache hit rate, in the CPU, first look for L1 Cache, if L1 Cache does not hit, continue to look for L2 Cache, and so on, finally did not find it directly from memory, and then add to the cache. Of course, when the CPU needs to write data to main memory, it will also flush the data in the register to the CPU cache first, and then flush the data to main memory.

Perhaps you have seen the shortcomings of this framework, in the single-core era there is only one processor core, read/write operations are completely completed by the single core, no problem; but multi-core architecture, a core modified main memory, the other core does not know that the data has been invalid, continue to use the main memory or their own cache layer data stupidly, then it will lead to data inconsistency. CPU hardware manufacturers also provide solutions to this problem, called cache coherence protocol (MESI protocol), cache coherence protocol this thing I do not understand, I do not know, so not BB here, interested can study on their own.

After talking about hardware memory architecture, let's focus back on our topic Java memory model. Let's talk about Java memory model together.

Java memory model

What is Java Memory Model? Java memory model can be understood as following the design of multi-core hardware architecture, using Java to implement a set of JVM-level "cache coherence," so that you can avoid the CPU hardware vendor standards are not the same risk. So, let's start with the Java memory model: Java memory model. Java Memory Model (JMM ), itself is an abstract concept, not as real as hardware architecture, it describes a set of rules or specifications, through this set of specifications define the variables in the program (including instance fields, static fields, and elements that make up array objects). For more information about Java memory model, read JSR 133: Java Memory Model and Threading Specification.

We know that the entity that runs the JVM program is a thread. In the previous JVM memory structure, we learned that when each thread is created, the JVM creates a working memory for it ( Java stack), used to store thread private data, and Java memory model stipulates that all variables are stored in the main memory, the main memory is a shared memory area, all threads can access, but the thread variable operations (read assignment, etc.) must be carried out in the working memory, first to copy the variable from the main memory to its own working memory space, and then to operate on the variable, after the operation is completed, write the variable back to the main memory, You cannot directly manipulate variables in main memory.

We know that Java stack is a private data area of each thread, and other threads cannot access the private data of different threads, so threads need to communicate, they must be completed through main memory. Java memory model is a set of specifications sandwiched between the two. Let's first take a look at this abstract architecture diagram:

image source network

From the structure diagram, if thread A and thread B need to communicate, they must go through the following two steps:

HarmonyOS Technology Community

First, thread A flushes the value from the copy of the shared variable in local memory A into main memory.

Thread B then goes to main memory to read the updated value of Thread A, so that the variable value in Thread A goes to Thread B.

Let's look at a specific example to deepen our understanding. Look at the following picture:

Now that thread A needs to communicate with thread B, we know that there are two parts to the communication between threads. Suppose that the x value in all three memories is 0 at the beginning. Thread A temporarily stores the updated value of x (assuming the value is 1) in its own local memory A when executing. When thread A and thread B need to communicate, thread A first flushes the modified x value from its local memory to main memory, where the x value becomes 1. Then, thread B goes to main memory to read the updated x value of thread A, and the x value of thread B's local memory also becomes 1, thus completing a communication.

JMM provides memory visibility guarantees for Java programmers by controlling the interaction between main memory and each thread's local memory. In addition to defining a set of specifications, the Java memory model provides a set of primitives that encapsulate the underlying implementation for direct use by developers. This implementation is also what we commonly use volatile, synchronized, final, etc.

Happens-Before memory model

The Happens-Before memory model may be more appropriately called the Happens-Before principle, which is defined in JSR 133: Java Memory Model and Thread Specification as an approximation of the Java memory model.

To facilitate programmer development and shield the underlying details, the Java memory model defines the Happens-Before principle. Once we understand the Happens-Before principle, we can solve variable visibility problems encountered in concurrent programming without understanding the memory operations at the bottom of the JVM. The Happens-Before principle defined by the JVM is a set of partial ordering relationships: for two operations A and B, the two operations can be executed in different threads. If A Happens-Before B, then it is guaranteed that, after operation A has been executed, the results of operation A will be visible to operation B.

There are 8 Happens-Before rules. Let's learn these 8 rules together.

1. Rules of procedure sequence

This rule means that in a thread, according to the program order, the previous operation Happens-Before any subsequent operation. This rule is still very easy to understand, look at the following code

class Test{ 1 int x ; 2 int y ; 3 public void run(){ 4 y = 20; 5 x = 12; } }

The fourth line of code should Happens-Before the fifth line of code, that is, in the order of the code.

2. Locking rules

This rule refers to the unlocking of a lock Happens-Before subsequent locking of the lock. For example, the following code, before entering the synchronization block, will automatically lock, and after the code block execution will automatically release the lock, lock and release lock are compiler to help us achieve

synchronized (this) { //automatic lock here // x is a shared variable, initial value =10 if (this.x

< 12) { this.x = 12; } } // 此处自动解锁 对于锁定规则可以这样理解:假设 x 的初始值是 10,线程 A 执行完代码块后 x 的值会变成 12(执行完自动释放锁),线程 B 进入代码块时,能够看到线程 A 对 x 的写操作,也就是线程 B 能够看到 x==12。 3、volatile 变量规则 这条规则是指对一个 volatile 变量的写操作及这个写操作之前的所有操作 Happens-Before 对这个变量的读操作及这个读操作之后的所有操作。 4、线程启动规则 这条规则是指主线程 A 启动子线程 B 后,子线程 B 能够看到主线程在启动子线程 B 前的操作。 public class Demo { private static int count = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() ->

{ System.out.println(count); }); count = 12; t1.start(); } }

Child thread t1 can see the main thread's changes to the count variable, so 12 is printed in the thread. This is the thread start rule.

5. Thread termination rules

This is about waiting threads. It means that main thread A waits for child thread B to complete (main thread A does this by calling child thread B's join() method), and when child thread B completes (main thread A's join() method returns), the main thread can see the child thread's operation. Of course, the so-called "see" refers to the operation of shared variables.

public class Demo { private static int count = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { // t1 thread modified variable count = 12; }); t1.start(); t1.join(); // mian thread can see t1 thread modified variables System.out.println(count); } }

6. Interruption rules

One thread calls interrupt on another thread, Happens-Before interrupted thread detects interrupt is called.

public class Demo { private static int count = 0; public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { // t1 Thread can see data before interrupt System.out.println(count); }); t1.start(); count = 25; // t1 Thread interrupted t1.interrupt(); } }

Thread t1's interrupt() method is called in the mian thread, and mian's modifications to count are visible to thread t1.

7. Terminator Rules

An object's constructor executes the end Happens-Before its finalize() method begins. "End" and "Start" indicate that, in time, an object's constructor must finish executing by the time its finalize() method is called. This principle ensures that all field values of an object are visible when its finalize method executes.

8. transitive rules

This rule says that if A Happens-Before B and B Happens-Before C, then A Happens- Before C.

At this point, the study of "what are the knowledge points of Java memory model" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report