Monday, July 18, 2011

synchronizedList

I have created an attribute

private List measurements = new ArrayList();

and I keep getting an exception:

java.lang.ArrayIndexOutOfBoundsException: 10
at java.util.ArrayList.add(ArrayList.java:352)


whenever I do

public void addEntry(long elapsed) {
measurements.add(elapsed);
}



In fact, ArrayList constructor does:

public ArrayList() {
this(10);
}


and its "add" method verifies that there is enough capacity:

public boolean add(E e) {
ensureCapacity(size + 1);
elementData[size++] = e;
return true;
}



it is self evident that this code is not thread safe.... so if you plan to use an ArrayList in a concurrent scenario, you better synchronize here and there...
otherwise use http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29

List list = Collections.synchronizedList(new ArrayList());

No comments: