I am writing tests for my program. Sometimes my tests work, and sometimes they fail. I am trying to trace all the sources of non-determinism.
Here is a simple, self-sufficient example of my problem:
import java.util.ArrayList; public class ArrayExceptions { public static void main(String[] args) { final int ITERATIONS = 10000; ArrayList<Integer> list = new ArrayList<>(); try { list.get(-1); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } for(int i = 0; i < ITERATIONS; i++) { try{ list.get(-1); } catch (ArrayIndexOutOfBoundsException e) { if(e.getMessage() == null) { System.out.println(i); break; } } } for(int i = 0; i < 10; i++) { try { list.get(-1); } catch(ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } } } }
This program creates an ArrayList. It tries to access element -1 repeatedly. Initially, this creates a detailed return line and message along with an ArrayIndexOutOfBoundsException. However, if you call it enough time (where "enough" seems to be around 5500), the return line and message are missing in the exception thrown.
The result of this program varies from run to run. Here it comes out early, at 5494 iterations:
java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(ArrayList.java:418) at java.util.ArrayList.get(ArrayList.java:431) at ArrayExceptions.main(ArrayExceptions.java:8) 5494 java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException
Here it fails, at 5540 iterations:
java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.ArrayList.elementData(ArrayList.java:418) at java.util.ArrayList.get(ArrayList.java:431) at ArrayExceptions.main(ArrayExceptions.java:8) 5540 java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException java.lang.ArrayIndexOutOfBoundsException
Why is he doing this?
source share