Java review-atomicity, visibility, order

Atomicity

Atomicity: One operation or multiple operations are either not executed, or all executed and the execution process is not interrupted by any factor.

A simple example is bank card transfer, A to B transfers, then the process of deducting money from A and adding money to B must be atomic. If it is not atomic, problems will arise.

Visibility

Visibility: When multiple threads access the same variable, as long as one thread modifies the value of this variable, other threads should be able to see it immediately.

Orderliness

Orderliness: that is, the order of program execution is executed in the order of code.

In order to improve the efficiency of the program, the JVM may rearrange the input code. That is to say, the order in which the virtual machine runs is not necessarily the order of the code you wrote. Although it will rearrange the instructions, it will ensure that the results of your program execution are the same as the results of the code execution. But instruction rearrangement can only guarantee that a single thread runs the same result, once it involves multiple threads.

//线程1:
context = loadContext();   //语句1
inited = true;             //语句2
 
//线程2:
while(!inited ){
    
    
  sleep()
}
doSomethingwithconfig(context);

如果线程1先执行了语句2,这时线程2会跳出循环,但是这时的context可能为null。

How to ensure the above three characteristics

Atomicity

For simple operations, atomicity can be guaranteed:

x = 10;         //语句1,原子性,直接赋值
y = x;         //语句2,无原子性,先取出x的值,再赋给y
x++;           //语句3,无原子性,与上同理
x = x + 1;     //语句4,无原子性,与上同理

To ensure a wider range of atomicity, you can use locks (synchronized and lock)

Visibility

volatile keyword. When modifying a variable, it can be guaranteed that the modified value of the variable can be immediately updated to the main memory for other threads to read.

Synchronized and lock can also be guaranteed, the principle is that only one thread can access the code block and variables at the same time.

Orderliness

Volatile can guarantee a certain degree of order, synchronized and lock can guarantee order, the code they lock can only be accessed by one thread at a time, and other threads cannot access it, and order is guaranteed in a certain sense.

Guess you like

Origin blog.csdn.net/why1092576787/article/details/114702965