How is ArrayOutOfBoundsException possible in String.valueOf(int)?

后端 未结 3 899
無奈伤痛
無奈伤痛 2021-02-05 03:30

Why does this code sometimes produce ArrayOutOfBoundsException? How is that even possible for String.valueOf(int)?

public static String ipToString(B         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 03:47

    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.

提交回复
热议问题