Why does array[idx++]+="a" increase idx once in Java 8 but twice in Java 9 and 10?

Solution 1:

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

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

It 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 array. 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), is in there twice. This is incorrect, as the spec says in jls-15.26.2:

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

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

So yes, this is a bug.


Some updates:

The bug is fixed in JDK 11 and was back-ported to JDK 10 (here and here), but not to JDK 9, since it no longer receives public updates.

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

Workaround: compile with -XDstringConcat=inline

That will revert to using StringBuilder to do the concatenation, and doesn't have the bug.