Learn JVM easily (II)-memory model, visibility, Command Re-sorting, jvm Model

Source: Internet
Author: User

Learn JVM easily (II)-memory model, visibility, Command Re-sorting, jvm Model

In the previous article, we introduced the basic running process and memory structure of JVM, and had a preliminary understanding of JVM, in this article, we will explore the visibility of variables in java based on the JVM Memory Model and the possibility of re-sorting of different java commands during concurrency.

Memory Model

First, let's think about how the next java thread needs to communicate with another thread. Then let's clarify the requirements, how can a java thread notify another thread of updates to a variable? We know that the instance objects and array elements in java are all placed in the java heap, And the java heap is shared by threads. (Java heap is called the main memory here), and every thread is its own private memory space (called working memory). If thread 1 needs to communicate with thread 2, it will certainly go through a similar process:

1. Thread 1 updates X in its working memory to 1 and refreshes it to the main memory;

2. Thread 2 reads the variable X = 1 from the main memory and updates it to its own working memory. Therefore, the X read by thread 2 is the value after thread 1 is updated.

From the above process, we can see that the communication between threads must go through the main memory, while the interaction between the main memory and the working memory requires the Java Memory Model (JMM) for the manager. Demonstrate how JMM manages master memory and working memory:

When thread 1 needs to refresh an updated variable value to the main memory, two steps are required:

1. store operations in the working memory;

2. write operations on the master memory;

After completing these two steps, you can refresh the variable values in the working memory to the primary memory, that is, the variable values in thread 1's working memory are consistent with those in the primary memory;

When thread 2 needs to read the latest value of the variable from the main memory, it also requires two steps:

1. The master memory performs the read operation to read the variable value from the master memory;

2. Execute the load operation in the working memory to update the read variable value to the local memory copy;

After completing these two steps, the variable value of thread 2 is consistent with that of the main memory.

Visibility

Java has a keyword volatile. What is its use? This answer is actually in the above-mentioned java thread communication mechanism. we can imagine that thread 1 and thread 2 will inevitably have a latency problem due to the emergence of the middle layer of the working memory, for example, thread 1 updates the variable in the working memory, but has not yet refreshed the master memory. At this time, the variable value obtained by thread 2 is the variable value that has not been updated, or thread 1 successfully updates the variable to the main memory, but thread 2 still uses the variable value in its working memory. In either case, Inter-thread communication may fail to achieve the expected purpose. For example:

// Thread 1 boolean stop = false; while (! Stop) {doSomething ();} // thread 2
stop 
= True;

In this classic example, thread 2 controls thread 1 interruption by modifying the stop value, but unexpected results may occur in the real environment. After thread 2 is executed, thread 1 is not immediately interrupted or even never interrupted. This is because the variable update of thread 2 to thread 1 cannot be obtained immediately.

However, when Volatile appears, it is no longer a problem. Volatile guarantees two things:

1. Variable updates in thread 1's working memory are forcibly written to the main memory immediately;

2. variables in the worker memory of thread 2 will be forced to expire immediately, so that thread 2 must obtain the latest variable value from the master memory.

So this understands that Volatile ensures the visibility of variables, because thread 1's modifications to variables can immediately make thread 2 visible.

Command Re-sorting

Let's take a look at the command Sorting code:

Int a = 0; optional boolean flag = false;

// Thread 1

Public void writer (){

A = 1;

Flag = true;

}

// Thread 2

Public void reader (){

If (flag ){

Int I = a + 1;

......}

}

Thread 1 executes a = 1 in sequence, flag = true; thread 2 determines that flag = true, sets I = a + 1, according to the code syntax, we may infer that the I value is equal to 2 at this time, because thread 2 has executed a = 1 when determining flag = true; therefore, the value of I is equal to a + 1 = 1 + 1 = 2, but the actual situation is not necessarily the case. The cause of this problem is that the two statements in thread 1 are a = 1; flag = true; it may be re-ordered for execution,

This is a simple demonstration of Command Re-sorting. The two value assignment statements, although their code order is one after the other, are not necessarily executed in the order of code. You might say, isn't there a mess with this command to reorder? The programs I write do not follow my code flow. How can this problem be solved? You can rest assured that your program will not be messy, Because java and CPU and memory have a set of strict command re-sorting rules, which can be reordered, and which cannot be reshuffled have rules. The following process demonstrates the reordering of a java program from compilation to execution:

In this process, the first step is the re-check of the compiler. The re-sorting of the compiler is strictly performed according to the JMM specification. In other words, the re-sorting of the compiler generally does not affect the correct logic of the program. Step 2 and Step 3 are processor re-sorting. It is difficult to manage the JMM for the processor re-sorting. What should I do? It requires the java compiler to add a memory barrier when generating commands. What is the memory barrier? You can think of it as an airtight protective cover that protects java commands that cannot be reordered, so the processor will not reorder the commands protected by memory barrier. These knowledge points are not described here as to where the memory barrier should be added and the types and functions of the memory barrier. For more information, see JVM specifications.

The following describes the logic that will not be reordered in the same thread:

In these three cases, the results of any change to the code order will be very different, and such logic code will not be reordered. Note that this means that a single thread will not be reordered. If it is in a multi-threaded environment, logic problems will still occur, for example, the first example.

Conclusion

This article briefly introduces the simple principle of java in implementing inter-thread communication, introduces the role of the volatile keyword, and finally introduces the possibility of Command Re-sorting in java. The next article will introduce the impact of JVM parameter settings on java programs.

 

References:

Actual Java Virtual Machine Ge yiming

Zhou Zhiming, a deep understanding of Java Virtual Machine (version 2nd)

Cheng Xiaoming, a deep understanding of the Java Memory Model

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.