If you are familiar with Java concurrency programming, you should know that there are memory visibility issues in the case of multi-threaded shared variables:
A variable is assigned in one thread, and the value of the variable is read in another thread, and the read may still be the previous value;
This is not to say the timing problem, for example, the read operation was performed before the assignment operation, but rather that
Even if you iterate over the value of the variable in another thread, you may never see the latest value of the variable, or you won't see it for a while.
Take a look at the following code slice
1 Public classMainextendsThread {2 Private Static BooleanFlag =false;3 4 @Override5 Public voidrun () {6 while(!flag);7 }8 9 Public Static voidMain (string[] args) {TenMain m =NewMain (); One M.start (); A Try { -Thread.Sleep (200); -}Catch(interruptedexception e) { the e.printstacktrace (); - } -Flag =true; - Try { + M.join (); -}Catch(interruptedexception e) { + e.printstacktrace (); A } atSystem.out.println ("Done"); - } -}
This code will not end up running in a hotspot under Windows,linux,macos.
If you declare the variable flag as volatile, the program ends normally,
Similar programs run under Android Dalvik no problem
Oddly, if you add a print statement, it can also end normally.
If you look at the bytecode, you find that the byte code is not different except for the volatile tag of the flag variable.
From here we can infer that is not the problem of bytecode execution, so the suspicion is the cause of the JIT, turn off the JIT, run again, and sure enough is normal.
If it is JIT, generated machine code, according to the CPU cache consistency protocol, the variable may not be visible for a short time, it should be visible over a period of time, the computer running at the same time so many programs, such as the store buffer structure should be flushed to the mix, even in memory , should not lead to permanent invisibility.
So what exactly is causing the permanent invisibility? is not a bytecode execution engine, it is not a hardware problem, the only possible is the JIT generated code caused.
So the next step is to look at the JIT code:
Analysis of a Java memory visibility problem