Bug in System.arraycopy()
843811Jan 31 2005 — edited Feb 4 2005After several thousand iterations on HotSpot Server VM 1.4.2_05, System.arraycopy()'s behavior appears to be inconsistent, in that the destiniation array is not always an exact copy of the source array. Also, once the point of failure is reached where the copy is incorrect, all subsequent copies are incorrect as well.
Try the following program!
===========================================
import java.util.Arrays;
public final class TestSysArrayCopy {
private static final int NUMBER_OF_ITERATIONS = 1000000;
private static final byte[] SOURCE_ARRAY = new byte[] {1, 0, 0, 0};
/* Running this program with the JVM commandline "-server"
* flag causes it to fail after several thousand iterations (on
* both WindowsXP and Linux). There does not appear to be
* a problem when running using the "-client" flag.
*/
public static void main(String[] args) {
for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
byte[] resultArray = copyByteArray();
if (!Arrays.equals(SOURCE_ARRAY, resultArray)) {
System.out.println("Iteration i = " + i
+ ": arrays are NOT equal: resultArray = "
+ getByteArrayString(resultArray));
break;
}
}
}
private static byte[] copyByteArray() {
int offset = (SOURCE_ARRAY[0] == 0) ? 1 : 0;
int length = SOURCE_ARRAY.length - offset;
byte[] resultArray = new byte[length];
System.arraycopy(SOURCE_ARRAY, offset, resultArray, 0, length);
return resultArray;
}
private static String getByteArrayString(byte[] array) {
String string = "{";
for (int i = 0; i < array.length; i++) {
string += (int)array;
if (i < array.length - 1) {
string += ", ";
}
}
string += "}";
return string;
}
}