I got different execution result from the follow code if the Simple class field a was modified by final keyword.
If the a is a final field , this program will normally exit; If it's a plain field, this program will keep running all the time.
This situation only occurs in C2 compiler .
I thought this situation is related to visibility of the flag field in multi-threads environment.However, I try to observed the assembly code by hsdis ,and found the difference between with and without final keyword.
I found nothing difference.
Actually, I know the storing "final" field would not emit any assembly instructions on x86 platform. But why this situation came out? Are there some particular operations I don't know ?
Thanks for reading.
class MultiProcessorTask {
private boolean flag= true;
public void runMethod() {
while (flag) {
new Simple(1);
}
}
public void stopMethod() {
System.out.println("change 'flag' field ...");
flag= false;
}
}
class ThreadA extends Thread {
private MultiProcessorTask task;
ThreadA(MultiProcessorTask task) {this.task = task;}
@Override
public void run() {
task.runMethod();
}
}
class Simple {
private int a; // modify "a" as "final"
Simple(int a) {this.a = a;}
}
public class TestRun {
public static void main(String[] args) {
MultiProcessorTask task = new MultiProcessorTask();
ThreadA a = new ThreadA(task);
a.start();
task.stopMethod();
System.out.println("it's over");
}
}
The disassembly code output:
- The
runMethod
in thefinal
case:
- The
runMethod
in thenon-final
case: