Deep parsing of Java Memory Model: reordering — to
Original address: http://www.codeceo.com/article/java-memeory-2.html
Data dependency
If two operations access the same variable and one of the two operations is a write operation, there is a data dependency between the two operations. There are three types of data dependencies:
In the above three cases, as long as the execution order of the two operations is reordered, the execution result of the program will be changed.
As mentioned earlier, compilers and processors may reorder operations. When reordering, the compiler and processor will abide by the data dependency, and the compiler and processor will not change the execution order of the two operations with data dependency.
Note that the data dependency mentioned here only refers to the instruction sequence executed in a single processor and the operation executed in a single thread. The data dependency between different processors and between different threads is not considered by the compiler and processor.
As if serial semantics
As if serial semantics means that no matter how reordering (compiler and processor to improve parallelism), the execution results of (single thread) programs cannot be changed. Compiler, runtime and processor must abide by as if serial semantics.
In order to comply with the as if serial semantics, compilers and processors will not reorder operations with data dependencies, because this reordering will change the execution results. However, if there is no data dependency between operations, they may be reordered by the compiler and processor. For specific instructions, please see the following code example for calculating circle area: