It's weird, but the code says more than words, so look at the test to see what I'm doing. In my current setup (updating Java 7 21 on 64-bit Windows) this test failed with an ArrayIndexOutOfBoundsException, but, replacing the test method code with the commented code, it works. And I wonder if there is any part of the Java specification that would explain why.
It seems to me, as Michael Nesterenko suggested, that the value of the array field is cached on the stack, before the method is called, and is not updated when it returns from the call. I can’t say if this is a JVM bug or a documented “optimization”. Multithreaded or "magic" is not involved.
public class TestAIOOB { private String[] array = new String[0]; private int grow(final String txt) { final int index = array.length; array = Arrays.copyOf(array, index + 1); array[index] = txt; return index; } @Test public void testGrow() {
Sebastien diot
source share