如何在String.valueOf(int)中使用ArrayOutOfBoundsException? [英] How is ArrayOutOfBoundsException possible in String.valueOf(int)?
问题描述
为什么这段代码有时会产生ArrayOutOfBoundsException?怎么可能 String.valueOf(int)
?
Why does this code sometimes produce ArrayOutOfBoundsException? How is that even possible for String.valueOf(int)
?
public static String ipToString(ByteString bs) {
if (bs == null || bs.isEmpty()) {
return null;
} else {
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.toString();
}
}
java.lang.ArrayIndexOutOfBoundsException: -81914
at java.lang.Integer.getChars(Integer.java:458)
at java.lang.Integer.toString(Integer.java:402)
at java.lang.String.valueOf(String.java:3086)
at com.mystuff.mypackage.ipToString(MyCode.java:1325)
...
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
更新
I发生这种情况时不知道字节的值,但似乎不应该有任何可能的字节值。
I don't know the value of the byte when this occurs, but it doesn't seem like it should be possible for any possible value of byte.
一旦发生一次,每次调用都会出错并出现相同的异常。
Once it happens once, every invocation then errors out with the same exception.
环境:
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)
推荐答案
这是一个JIT JDK 8u20中引入的编译器错误是另一个修复的副作用:
JDK -8042786
This is a JIT compiler bug that has been introduced in JDK 8u20 as a side-effect of another fix:
JDK-8042786
问题与自动装箱消除优化有关。
解决方法是关闭优化 -XX:-EliminateAutoBox
JVM标志
The problem is related to auto-boxing elimination optimization.
The work-around is to switch the optimization off by -XX:-EliminateAutoBox
JVM flag
在最新的JDK 9源代码库中看起来也存在这个问题。
我已经提交了错误报告: https://bugs.openjdk.java.net / browse / JDK-8058847 包含100%可重现的最小测试用例。
Looks like the problem also exists in the most recent JDK 9 source base.
I've submitted the bug report: https://bugs.openjdk.java.net/browse/JDK-8058847 with 100% reproducible minimal test case included.
这篇关于如何在String.valueOf(int)中使用ArrayOutOfBoundsException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!