java – Why array [idx ++] + = “a” increases idx once in Java 8 but sometimes in Java 9 and 10?

This is a bug in javac starting with JDK 9 (which made some changes regarding string concatenation, which I suspect is part of the problem), as confirmed by the team javac with bug id JDK-8204322 . If you look at the corresponding bytecode for the line:

array[i++%size] += i + " ";

IS:

  21: aload_2
  22: iload_3
  23: iinc          3, 1
  26: iload_1
  27: irem
  28: aload_2
  29: iload_3
  30: iinc          3, 1
  33: iload_1
  34: irem
  35: aaload
  36: iload_3
  37: invokedynamic #5,  0 // makeConcatWithConstants:(Ljava/lang/String;I)Ljava/lang/String;
  42: aastore

Where the last aaload is the actual load from the matrix. However, the part

  21: aload_2             // load the array reference
  22: iload_3             // load 'i'
  23: iinc          3, 1  // increment 'i' (doesn't affect the loaded value)
  26: iload_1             // load 'size'
  27: irem                // compute the remainder

Which roughly corresponds to the expression array[i++%size] (minus the actual load and store), it’s in there twice. This is incorrect, as the specification says in jls-15.26.2 :

A compound assignment expression of the shape E1 op= E2 equivalent to E1 = (T) ((E1) op (E2))where is it T is the kind of E1, except that E1 it is evaluated only once.

So, for the expression array[i++%size] += i + " ";the part array[i++%size] it only needs to be evaluated once. But it is rated twice (once for the cargo and once for the store).

So yes, this is a bug.


Some updates:

The bug was fixed in JDK 11 and there will be a back-port to JDK 10 (but not JDK 9, since no longer receives public updates ).

Aleksey Shipilev mentions on the JBS page (and @DidierL in the comments here):

Solution: compile with -XDstringConcat=inline

This will return to use StringBuilder to do the concatenation and does not have the bug.

Leave a comment