Vectors … read the small print

16 11 2007

Well I thought Vectors were synchronized. The Object is, but Iterators are not.

From the Java Doc

” The Iterators returned by Vector’s iterator and listIterator methods are fail-fast: if the Vector is structurally modified at any time after the Iterator is created, in any way except through the Iterator’s own remove or add methods, the Iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by Vector’s elements method are not fail-fast. ”

Hence, create an iterator on a vector and you will get a ConcurrentModificationException on the iterator if the vector is modified, even though the Vector itself is Synchronized.



2 responses

16 11 2007
Aaron Zeckoski

You will want to use this if you need a thread safe iterator:

It is too slow to be used for anything else really. The alternative is to simply make your own copy and then iterate.

16 11 2007
Ian Boston

Since CopyOnWriteArrayList is slow as you point out I am looking at using a ConcurrentHashMap with key = value for the occasions where there is heavier write traffic, and the CopyOnWriteArrayList where I know there are minimal writes to the array.

Since I know that the List should be unique, I think this will solve the problem.

%d bloggers like this: