JVM Learning-(ii) memory model, visibility, command reordering

Source: Internet
Author: User
Tags visibility volatile

We will explore the visibility of variables in Java based on the JVM's memory model and the possible reordering of instructions that may occur when different Java instructions are concurrent.

Memory model

First we think about a Java thread to communicate to another thread, what to do, let's make it clear, how does one Java thread update a variable to another thread? We know that instance objects and array elements in Java are placed in the Java heap, and the Java heap is thread-shared. (We refer to the Java heap as the main memory), and each thread is its own private memory space (called working memory), if thread 1 is to communicate to thread 2, it will go through a similar process:

1. Thread 1 updates the x in its working memory to 1 and flushes it into main memory;

2, thread 2 reads the variable x=1 from the main memory, updates to its own working memory, so that thread 2 reads x is the thread 1 updated value.

From the above process, the communication between the threads needs to go through main memory, and the main memory interacts with the working memory, then the Java memory Model (JMM) is needed to manager. Demonstrates how JMM manages main memory and working memory:

When thread 1 needs to flush an updated variable value into main memory, there are two steps to be followed:

1, working memory execution store operation;

2, the main memory to perform write operation;

By completing these two steps, the variable values in the working memory are flushed to the main memory, which is the same as the variable values of the thread 1 working memory and the main memory;

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

1, the main memory to perform a read operation, the value of the variable from the main memory read out;

2, the working memory performs the load operation, updates the Read variable value to the local memory copy;

With these two steps, the variable values for thread 2 and main memory are consistent.

Visibility of

There is a keyword volatile in Java, what's the use of it? This answer is actually in the above-mentioned Java thread Communication mechanism, we imagine that due to the presence of the middle layer of working memory, thread 1 and thread 2 must have a delay problem, such as thread 1 in the working memory update the variable, but not yet flushed to the main memory, While thread 2 Gets the value of the variable that is not updated, or thread 1 succeeds in updating the variable to main memory, thread 2 still uses the value of the variable in its own working memory, which can also cause problems. Whatever happens, it can cause communication between threads to fail to achieve the intended purpose. For example, the following example:

Thread 1 Boolean stop = false; while (!stop) {dosomething ();}//Thread 2
= true;

This classic example indicates that thread 2 controls thread 1 interrupts by modifying the value of stop, but in real-world situations there may be unexpected results, thread 2 after execution, thread 1 is not immediately interrupted or even uninterrupted. This behavior occurs because thread 2 's variable update to thread 1 is not available for the first time.

But this is not a problem until after the advent of the volatile, volatile guarantee two things:

1, the variable update in thread 1 working memory forces the write to main memory immediately;

2, thread 2 in the working memory of the variables will force the immediate invalidation, which makes thread 2 must go to the main memory to get the latest variable value.

So this makes sense that volatile guarantees the visibility of variables because thread 1 changes the variables to make thread 2 visible the first time.

Order reordering

About order ordering Let's look at a piece of code first:

int a = 0;? 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,flag=true in turn, thread 2 determines to Flag==true, sets i=a+1, according to code semantics, we may infer that the value of I is equal to 2, because thread 2 in the judgment of Flag==true, thread 1 has executed a=1; So the value of I equals a +1=1+1=2, but the real situation is not necessarily the case, the cause of this problem is thread 1 internal two statements a=1;flag=true; may be reordered to execute,

This is a simple demonstration of order reordering, with two assignment statements although their code order is one after the other, they are not necessarily executed in code order when they are actually executed. You might say, there's this order reordering. I write the program does not follow my code flow, how to play? This you can rest assured that your program will not mess up, because Java and CPU, memory has a set of strict command reordering rules, which can be re-ranked, which cannot rearrange the rules. The following process illustrates what sort of reordering a Java program will undergo from compilation to execution:

In this process, the first step is compiled by the compiler to troubleshoot, the compiler will be sorted according to the specifications of JMM strict, in other words, compilers generally do not affect the correct logic of the program. The second to third step belongs to the processor reordering, the handler is not jmm, how to do? It will require the Java compiler to add a memory barrier when generating instructions, what is the memory barrier? You can understand that a non-ventilated shield protects the Java commands that cannot be reordered, so the processor does not reorder it when it encounters a memory barrier-protected instruction. The knowledge points about where to add memory barriers, what kinds of memory barriers, and what they do, are not explained here. You can refer to the JVM specification for relevant data.

Here's a look at the logic that will not be reordered in the same thread:

In these three cases, arbitrarily changing the order of one code, the result will be very different, for such logic code, is not reordered. Note that this means that a single thread will not be reordered, and if in a multithreaded environment, there will still be logic problems, such as the example we started with.

Conclusion

This paper briefly introduces the simple principle of Java in implementing the communication between threads, and introduces the function of the volatile keyword, and finally introduces the possibility that the command reordering can occur in Java. The next article describes the effect of the parameter settings in the JVM on the Java program.

JVM Learning-(ii) memory model, visibility, command reordering

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.