How to understand that instruction reordering has no effect on single threading?

how to understand instruction reordering has no effect on single thread, it will not affect the running result of the program, but it will affect multi-thread.

for example:

int i = 0; //1
i = i + 1; //2
System.out.println(i); //3

if reordering is performed and the order of execution of 2 and 3 is changed, it will definitely affect the result of the run.

Mar.09,2021

first of all, you need to understand the meaning of instruction reordering: the processor is as efficient as possible without affecting the final calculation result.
how to make sure that the final calculation result is not affected? When calculating, there is a data dependency, such as the printf, here, which depends on the data I and does not output until I completes the final calculation. Or the calculation of the variable value I must be happens-before printf.
JMM (java's memory model) is special, the happens-before relationship is very important, you can learn about it.


instruction rearrangement is not a disorder, 2 3 dependency is not reversed.
single-threaded instructions can be considered to be executed serially, and only

is rearranged.
a = 1; // 1
b = 2; // 2
System.out.println(a); // 3
System.out.println(b); // 4

like 1 2 can be reversed without affecting the result. 1 3 , 2 4 and 3 4 will not.


you will know that


instruction rearrangement has an important premise in a single-threaded environment, instruction rearrangement cannot affect the final result , so you can't rearrange it here.

Menu