We know it can in JavaScript.
But is it possible to print \"Success\" message on the condition given below in Java?
if (a==1 && a==2 &&am
Inspired by the @Erwin's excellent answer, I wrote a similar example, but using Java Stream API.
And an interesting thing is that my solution works, but in very rare cases (because just-in-time compiler optimizes such a code).
The trick is to disable any JIT optimizations using the following VM option:
-Djava.compiler=NONE
In this situation, the number of success cases increases significantly. Here is the code:
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");
}
}
}
P.S. Parallel streams use ForkJoinPool under the hood, and variable a is shared between multiple threads without any synchronization, that's why the result is non-deterministic.