Reordering of Java Memory models

Source: Internet
Author: User

When executing a program, in order to provide performance, the processor and compiler will often reorder the instructions, but not arbitrarily re-ordering, not how you want to sort the order, it needs to meet the following two conditions:

    1. In the single-threaded environment can not change the results of the program operation;
    2. There is no allowed reordering of data dependencies

If you have seen the LZ on the blog will know, in fact, these two points can be attributed to one point: cannot be deduced through the Happens-before principle, jmm allow arbitrary ordering.

As-if-serial semantics

As-if-serial semantics means that all operations can be reordered for optimization, but you must ensure that the results of the reordering are not changed, and that the compiler, runtime, and processor must obey the as-if-serial semantics. Note that as-if-serial only guarantees single-threaded environments and is not valid in multithreaded environments.

Let's use a simple example to illustrate the following:

int a = 1< Span class= "PLN" > ;//aint b =  2 ;//bint C =  a + B;//c               

A, B, c three operations have the following relationship: A, B There is no data dependency, A and C, B and C have data dependencies, so in order to reorder, a, B can be arbitrarily ordered, but must be in front of C, the execution order can be a–> b–> C or b–> a – > C. But no matter what order of execution The final result C is always equal to 3.

The As-if-serail semantics protects the single-threaded program, which guarantees that the final result of the procedure is always consistent under reordering.

In fact, for the previous section of the code, they have such a happen-before relationship:

    1. A Happens-before B
    2. B Happens-before C
    3. A Happens-before C

1, 2 is the sequence of program order rules, 3 is transitivity. However, it is not said that by reordering, B may be ranked before a execution, why there is a Happens-beforeb? Here again it is stated that a Happens-before B is not a must be executed before B, but a is visible to B, but the result of the execution of this program A does not need to be visible to B, and they are reordered without affecting the result, so JMM will not consider this reordering illegal.

We need to understand this: to maximize the operational efficiency of the program without changing the results of the program execution.

Let's take a look at some interesting code:

Public Class RecordExample1 { Public Static voidMain(String[]Args){ IntA= 1; IntB= 2; Try {A= 3; AB= 1 / 0; //b } catch   (exception E { }  { system.out. ( "a ="  + A } }}  /span>                 

According to the reordering rules, the operation A and Operation B may be reordered, if the reorder, B will throw an exception (/by zero), at this time a statement will not be executed, then a will also be equal to 3? If you follow the as-if-serial principle, it changes the results of the program. In fact, the JVM has done a special processing of exceptions, in order to ensure as-if-serial semantics, Java exception handling mechanism for the reordering of a special processing: The JIT will be re-ordering in the Catch statement to insert the error compensation code (A = 3), While this can complicate the logic inside CATHC, the JIT optimization principle is to optimize the logic of the program as much as possible, even at the cost of complex catch block logic.

The effect of reordering on multithreading

In a single-threaded environment, because of as-if-serial semantics, reordering cannot affect the final result, but for multithreaded environments?

The following code (the classic use of volatile):

Public Class RecordExample2 { IntA= 0; BooleanFlag= False; /** * A thread execution */ Public voidWriter(){A= 1; 1Flag= True //2 }  /** * b thread execution */ public void  Read () { if ( flag) { //3 int I = a +  A;//4 } }                /span>                

A thread executes writer (), thread B executes read (), and thread B can read a = 1 at execution time? The answer is not necessarily ( Note: X86CPU does not support write-write reordering, if it is in the x86 above operation, this will certainly be A=1,lz did not test out for a long time, the last to find information only found ).

Because there is no data dependency between operations 1 and 2, it is possible to reorder processing, there is no data dependency between operations 3 and 4, and they can be reordered, but there is a control dependency between action 3 and Operation 4. If you reorder between Operation 1 and Operation 2:

In this order of execution thread B must not read the A value of thread a set, where the semantics of multithreading have been broken by reordering.

Operation 3 and Operation 4 can also be reordered, here is not elaborated. But there is a dependency relationship between them, because only operation 3 is set up for Operation 4 to execute. When there is a control dependency in the code, it affects the degree of parallelism of the execution of the instruction sequence, so the compiler and the processor use guessing execution to overcome the effect of control dependencies on the degree of parallelism. If Operation 3 and Operation 4 are reordered, Operation 4 is executed first, the result is temporarily saved to the reorder buffer and the result is written to the variable I when operation 3 is True

With the above analysis, reordering does not affect the execution results of single-threaded environments, but it destroys the execution semantics of multithreading .

Resources
    1. Zhou Zhiming: "In-depth understanding of Java virtual machines"
    2. Fang Fei: "The Art of Java concurrent programming"

Reordering of Java Memory models

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.