The happens-before and reordering of the Java memory model

reordering

In order to provide performance, processors and compilers often reorder instructions when executing programs, meeting the following two conditions:

  1. The result of program execution cannot be changed in a single-threaded environment;
  2. Reordering is not allowed if there are data dependencies

happens - before

Principle Definition

    1. If one action happens-before another action, the result of the first action will be visible to the second action, and the first action will be executed before the second action.
    1. The existence of a happens-before relationship between two operations does not mean that they must be executed in the order specified by the happens-before principle. If the execution result after reordering is consistent with the execution result according to the happens-before relationship, then this kind of reordering is not illegal.

principle rule

  1. Program order rule: In a thread, according to the code order, the operation written in front occurs first before the operation written in the back;
  2. Locking rules: an unLock operation occurs first and then faces the same lock operation;
  3. volatile variable rule: a write operation to a variable occurs first before a subsequent read operation of the variable;
  4. Delivery rule: If operation A occurs first in operation B, and operation B occurs in operation C first, it can be concluded that operation A occurs first in operation C;
  5. Thread start rules: The start() method of the Thread object occurs first for each action of this thread;
  6. Thread interrupt rules: The call to the thread interrupt() method occurs first when the code of the interrupted thread detects the occurrence of the interrupt event;
  7. Thread termination rule: All operations in the thread occur first in the thread termination detection. We can detect that the thread has terminated execution through the end of the Thread.join() method and the return value of Thread.isAlive().
  8. Object finalization rules: the initialization of an object occurs first at the beginning of its finalize() method;

Link

[Dead Java Concurrency] - Reordering of Java Memory Model

[Dead Java Concurrency] - happens-before of the Java memory model

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325127730&siteId=291194637