Home » Java » Easy to explain the happens-before principle

Easy to explain the happens-before principle

In the next narrative, I'll first explain what the happens-before rule is for, and then explain the happens-before rule with a simple little program

1, happens-before rule


we write programs should be optimized (compiler and processor of our program is optimized to improve operation efficiency) will be running, the optimization is divided into many types, including an optimization called reordering, reordering need to comply with happens-before rules, not to say how you want to row row, if that would not be confusing.


Part

happens-before rules are as follows:


1, program sequence rules: each operation in a thread is happens-before in any subsequent action of that thread


2, monitor lock (synchronization) rule: for a monitor's unlock, happens-before is then locked to the monitor


note 1: why is part happens-before principle, because this article is to let you understand the happens-before principle, I will try to let you focus on this matter, not affected by other


Note 2:

happens-before said each operation sequence rules in this thread in any subsequent operation is not to say that the previous operation must be performed before after an operation, but the results before the implementation of an operation must be visible to an operation, if it is not satisfied this requirement allow these two operations to re rank


two example: the function of the following method is to calculate a rectangular area of



, public, double, rectangleArea (double, length, double, width) {
Double leng;
Double wid;
Leng=length; //A
Wid=width; //B
Double area=leng*wid; //C
Return area;
}





The operation above

may optimize the compiler and the processor before running,


in program


A happens-before B


B happens-before C


The

A happens-before C //happens-before has a transfer rule


, according to the happens-before rule, we analyze the possible results after reordering


for B, so the A operating results of Leng must be visible to the B operation, but now B does not use length, so these two operations can be reordered, the A operation and C operation can sort weight, if the A operation and C operation were reordered because Leng is not valued, so leng=0, area=0*wid or area=0; the result is obviously wrong, so the operation is not A and C operation to re rank the results (Note 2 this is said before the implementation of an operation must be visible to Hou Yi if the operation does not meet this requirement will not allow the two operation reordering)


THE, END!
!






copyright notice: This article is original article for blogger. Without permission from blogger,.

must not be reprinted

Latest