Reordering the Java Compiler

Today I read the answers to the questions about the java interview, and I read this question: Question. Consider the following piece of Java code that initializes two variables, both of which are not volatile, and the two threads T1 and T2 change these values ​​as follows: both are not synchronized

int x = 0;
boolean bExit = false;

Thread 1 (not synchronized)
x = 1; 
bExit = true;

Thread 2 (not synchronized)
if (bExit == true) 
System.out.println("x=" + x);

Now tell us, is it possible for Thread 2 to print "x = 0"?

So the answer is yes. The explanation is "because without any instruction for the compiler, for example, synchronized or volatile, bExit = true may appear before x = 1 in the reordering of the compiler." Before that, I do not know that the compiler can execute one line before another line after it.

? , - - , , , ( )? ( , , ). - - ?

+4
3

JIT- * , Java.

x = 1;
bExit = true;

bExit = true;
x = 1;

, , .. , , . ( , , , , , .)

. , bExit x , ( ) , , bExit ( ) x.

* : Java- ( .java .class) , JIT- ( .class ) . Java , , .

x = 1;
bExit = true;
x = 2;

x = 1;

+5

, - "x = 0" -:   -   - x 1 bExit , bExit. , bExit , x, x, 0. , . .

+2

. , Java- .

:

int x = 0;
boolean bExit = false;

, . , , . X

, , :

  • x = 1;
  • bExit = true;
  • if (bExit == true) < - , if.
  • System.out.println("x=" + x);

. Java- :

  • 1, 2, 3, 4. x 1, bExit true, bExit , "x = 1"
  • 1, 3, 2. x 1, bExit 3. (4, , ), bExit true.
  • 3, 1, 2. , 4, x 1, bExit true.

Basically, you cannot just embed the if statement in multi-threaded programs and expect it to work as planned.

0
source

All Articles