How does the on-time compiler optimize concurrent Java threads?

An interesting question was asked some time ago :

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

I decided to prove that this is possible using the Java 8 Stream API (more precisely, parallel streams). 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 this is due to the optimization of the JIT compiler? So I tried to run the code with the following VM option:

-Djava.compiler=NONE

I disabled JIT and the number of successful cases has increased significantly!

How does the on-time compiler optimize parallel threads so that optimization can affect the execution of the above code?

+4
source share
1 answer

. , .

a volatile, JIT ( !) .

    a = 1;
    a = 2;
    a = 3;

    a = 3;

, JIT- if (a == 1 && a == 2 && a == 3) if (false), testValue() .

, .
-XX:CompileCommand=print,Race::lambda$main$0.

  # {method} {0x000000001e142de0} 'lambda$main$0' '(I)V' in 'Race'
  # parm0:    rdx       = int
  #           [sp+0x20]  (sp of caller)
  0x00000000052eb740: sub     rsp,18h
  0x00000000052eb747: mov     qword ptr [rsp+10h],rbp  ;*synchronization entry
                                                ; - Race::lambda$main$0@-1 (line 8)

  0x00000000052eb74c: mov     r10,76b8940c0h    ;   {oop(a 'java/lang/Class' = 'Race')}
  0x00000000052eb756: mov     dword ptr [r10+68h],3h  ;*putstatic a
                                                ; - Race::lambda$main$0@9 (line 10)

  0x00000000052eb75e: add     rsp,10h
  0x00000000052eb762: pop     rbp
  0x00000000052eb763: test    dword ptr [3470000h],eax
                                                ;   {poll_return}
  0x00000000052eb769: ret

eplilogue , 3:

  mov     dword ptr [r10+68h],3h  ;*putstatic a

, , System.out.println . , "", , JIT.

+5

Source: https://habr.com/ru/post/1693373/


All Articles