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)
Updates
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.
Environment:
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)
Integer.toString
must not fail. – ReinoldInteger.toString
is failing somehow! – Hydroscopeint
would have to be resilient even to that. – ReinoldStringBuilder
code. – Reinoldbyt
is. I suggest echoingbyt & 0xFF
to the console just before that line, so that you can catch the last one before it blows up. Then try a minimal program that just invokesString.valueOf()
on that byte value, and see what happens. – Hydroscopebyte
: the code is bulletproof, the only thing that could trigger that issue would be a bug in JVM. – Supperjmh
benchmark utilizing all 4 cores to do work like in the question, going through allbyte
values, no exceptions. – Reinoldbyt & 0xFF
is intentional. It is the standard way to interpret the byte as an unsigned 8-bit integer. – Reinold-81914
or does that number change? – Turnkey