Some time ago an interesting question had been asked:
Can (a == 1 && a == 2 && a == 3) evaluate to true in Java?
I decided to prove that it is possible using Java 8 Stream API (parallel streams, to be precise). Here is my code that works in very rare cases:
class Race {
private static int a;
public static void main(String[] args) {
IntStream.range(0, 100_000).parallel().forEach(i -> {
a = 1;
a = 2;
a = 3;
testValue();
});
}
private static void testValue() {
if (a == 1 && a == 2 && a == 3) {
System.out.println("Success");
}
}
}
And then I thought, maybe it's because of potential JIT compiler optimizations? Therefore, I tried to run the code with the following VM option:
-Djava.compiler=NONE
I disabled the JIT and the number of success cases has increased significantly!
How does just-in-time compiler optimize parallel streams so that the optimization might impact the above code execution?