Can (a==1 && a==2 && a==3) evaluate to true in Java?

后端 未结 8 741
梦如初夏
梦如初夏 2020-11-29 15:01

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         


        
8条回答
  •  孤城傲影
    2020-11-29 15:31

    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.

提交回复
热议问题