Why does this code sometimes produce ArrayOutOfBoundsException? How is that even possible for String.valueOf(int)
?
public static String ipToString(B
I can reliably reproduce your issue with this code:
public class Main
{
public static StringBuilder intToString(byte[] bs) {
final StringBuilder sb = new StringBuilder();
boolean started = false;
for (Byte byt : bs) {
if (started) sb.append(".");
sb.append(String.valueOf(byt & 0xFF));
started = true;
}
return sb;
}
public static void main(String[] args) {
final byte[] bs = {-2, -1, 0, 1, 2};
while (true) intToString(bs);
}
}
The issue will almost certainly be traced to a JIT compiler bug. Your observation that, once it happens the first time, it happens reliably on every subsequent call, points cleanly to a JIT compilation event which introduces the buggy code into the codepath.
If that's available to you, you could activate diagnostic JVM options which will print all compilation events (-XX:PrintCompilation
). Then you may be able to correlate such an event with the moment when the exception starts appearing.