Today I read java interview questions and I read this question: Question : Consider the following Java code snippet, which is initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, 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". In the explanation there is "because without any instruction to compiler e.g. synchronized or volatile, bExit=true might come before x=1 in compiler reordering." Before that I don't know that the compiler can execute one line before another line after it.
Why is this reordering ? And what if I print something to the console from different thread - the line that is supposed to be print first will be print after the line that is supposed to be print second (if they are printed from the same thread) ? It's weird to me (maybe, because I saw this thing for reordering for the first time). Can someone give some explanation ?
int x = 0;and then the second thread could executebExit == true; There is no reordering, there is only two threads executing. Reordering would occur if, and when, synchronization is implemented. Don't make assumptions about what two threads will do independently of each other. For example, one invalid assumption is that the same code will always take the same amount of time to execute in two different threads.x=0will ever be printed.x=1;the main thread executes both statements, thread 1 executesbExit = true;thread 2 executes both statements.