Three characteristics of concurrent programming in Java

1. Atomicity

概念: One operation or multiple operations as a whole, either all are executed and must be executed successfully, or not executed. The simple understanding is that the execution of the program is in place in one step, not distributed .

In Java, direct read operations and assignments (constants) are atomic operations . For operations that are not originally atomic, we can use the synchronized keyword or the Lock interface to ensure that only one thread executes the same string of code at the same time, which is also atomic.

2. Orderliness

概念: There is a certain sequence of program execution. In the Java memory model, in order to improve performance, the compiler and processor will reorder program instructions. In a single thread, reordering will not affect the correctness of the program, but in concurrent programming, it may get wrong results.
Insert picture description here
Used in java volatile关键字to ensure certain orderliness .
The following table shows the volatile reordering rules formulated by JMM for the compiler:

Can reorder Operation two Operation two Operation two
Operation one Ordinary read and write volatile read volatile write
Ordinary read and write no
volatile read no no no
volatile write no no

Alternatively, you can use synchronized关键字or Lock接口to ensure the orderly.

3. Visibility

概念: In my understanding, visibility means that after a shared variable is modified by a thread, the modified value can be immediately obtained when another thread accesses it.

Ordinary, unmodified shared variables cannot guarantee visibility. We can still use the synchronized keyword and the Lock interface to ensure visibility, and we can also use volatile.

当一个共享变量被volatile修饰时,就可以保证:
1. After a thread modifies any shared variable, any other thread accesses the variable again will get the latest value.
2. Not only is the modified value visible to the rest of the threads, the value before the modification is still visible.

The JSR-133 memory model uses the happens-before principle to explain the visibility between threads. If an operation is visible to another operation, then they must conform to the happens-before principle: In
程序顺序规则a thread, according to the code sequence, the operation written in the front occurs first and the operation written in the back
监视器锁规则: an unLock operation occurs first The lock operation on the same lock is performed later.
volatile域规则: The write operation to a variable occurs first in the subsequent read operation to this variable
传递性规则: if operation A occurs in operation B first, and operation B occurs in operation C first, then it can be concluded that operation A occurs in operation C first.

In concurrent programming, the atomicity, order and visibility of the program must be guaranteed at the same time to ensure the correctness of the program.

Guess you like

Origin blog.csdn.net/m0_46550452/article/details/107395103