Java multi-threading of the first occurrence of the principles (happens-before)

This article first micro-channel public number: Hu codeword

Introduced in front of Java memory model and memory barriers related concepts, the article then introduces multi-threaded programming is another important concept: Principles (happens-before) first occurs.

importance

It happens-before data is the main basis to determine whether there is competition, whether the thread safe, by this principle, we can solve all the problems the possibility of conflict exists between two concurrent operating environment.

What happens-before is

It Java memory model partial order for the two operations defined. A first example, the operation occurs in Procedure B, then B may be observed that all operations affecting the operation of the generated A, These include modifying values ​​of shared variables in memory, the message transmission, method calls, and the like.

for example:

//该操作在线程1中执行
i = 1;

//该操作在线程2中执行
j = i;

//该操作在线程3中执行
i = 2
复制代码

The above examples have shared variables i and j, the operation executed in the thread is assumed that "i = 1" in operation before the thread 2 "j = i" occurs, that shared value of variable j is 1 certainly.

This conclusion is because, according happens-before principles: "i = 1" operation may be observed, and the thread 3 has not yet begun.

If the operation is still assumed that "i = 1" and the operation "j = i" relationship first occurred, and the thread between 2 starts at 3 thread 1 and thread, there is no relationship between the first thread 2 and thread 3, the last variable j value is how much? The result may be 1 may be two. Thread 3 affect this case the variable i may be observed that thread B, may not be observed when the thread B is not observed, the thread B will be read to the old outdated data, this time there have been multi-threaded security issues.

happens-before rule 8

Java memory model already exists in eight first-defined rules occurs, these rules do not require any synchronization occurs first operation already exists, if the relationship between the two operations these days are not rules or can not be deduced by these few rules out, that there is no order of these two operations security, virtual machines can rearrange them.

Specific operation is as follows:

  1. Program sequence rules: In the same thread, according to the order of the program code, with the preceding operation EDITORIAL write back operation (control flow sequence: branch, loop, etc.).
  2. Lock rule: a first unlock operation occurs later (in time) Lock the lock operation on the same
  3. volatile variable rules: Write operations on a volatile variable first occurred in the face of this variable after the read operation
  4. Thread start rule: start Thread object () method first occurrence of this thread for each operation
  5. Thread terminates rules: All operations are ahead of thread termination occurs in the detection of this thread (the thread can wait by Thread.join () end, Thread.isAlive () return value).
  6. Thread break the rules: The code calls interrupt event thread interrupt () method to detect the occurrence of the first thread to be interrupted
  7. Begin initialize an object ahead of the completion of finalize occurred in the object () method: Object end rule
  8. Transitivity rule: if the operation occurs ahead A Procedure B, B ahead operation occurs in the procedure C, the operation that occurs in the operation preceding to A C

happens-before rule examples

Let's see how these rules to determine whether a sequence example among operated by, for reading and writing shared variables and operations, whether the site is secure.

private int value = 0;

public void setValue(int value) {
    this.value = value;
}

public int getValue() {
    return this.value;
}
复制代码

This example is a very simple code, assuming there is a thread 1 and thread 2, thread 1 first (time to) call the "setValue (1)", then thread 2 calls the "getValue ()", the final value of the thread 2 get is How many?

We have to analyze the rules according to eight previously mentioned:

  • Since both methods are executed in the thread 1 and the thread 2, a thread is not the same, the program sequence rules NA
  • No sync code block (locked), the lock thus not applicable rules
  • Code value variable non-volatile variables, so volatile variable rule does not apply
  • Obviously the whole implementation process and thread startup, termination, interruption, object finalization rule does not matter
  • Because there is no advance a relationship, it does not apply to the transfer rules

Based on the analysis above, although the timing of the thread 1 in operation before the thread 2, but because there is no advance a relationship, it is not possible to determine thread 2 "getValue ()" value, the operator of the two threads together is unsafe.

To solve this problem is very simple, one is setValue and getValue two methods are defined as synchronized method, so that you can lock rules apply, the other is to define the value variable as volatile variables, and modify the value where the value of time It does not depend on value of the original value, so we can apply volatile variable rules.

Through the above analysis, we know that an action "occurs first in time" does not mean that this operation will be "first occurs."

An action that "first occurrence" is not "is also the first time the occurrence of" Well, this is actually not guaranteed, a typical example is the command rearrangements, such as the following examples:

//下面两个操作在同一个线程中执行
int i = 1;  //操作1
int j = 2;  //操作2
复制代码

In the above example, the thread in accordance with the rules of order, the operation correctness of the operation occurred 1 2 ahead, but probably because the operation 2 the reordering is performed first during actual execution of the processor, so that there is no prejudice to the first occurrence, because in this thread, we can not perceive this change.

to sum up

The first time on the order of occurrence of no fundamental relationship between principles, so we do not measure the thread-safe or not when attention chronological order, but should focus on the principle of first occurrence.



Here is my personal number of the public are welcome to exchange concerns

Guess you like

Origin juejin.im/post/5d030db7f265da1b8e709b73