Vectors … read the small print

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.

Comments

2 Responses to “Vectors … read the small print”

  1. Aaron Zeckoski on November 16th, 2007 5:35 pm

    You will want to use this if you need a thread safe iterator:
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html

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

  2. Ian Boston on November 16th, 2007 6:41 pm

    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.

Leave a Reply




This is a captcha-picture. It is used to prevent mass-access by robots. (see: www.captcha.net)

You must read and type the 5 chars within 0..9 and A..F, and submit the form.

  

Oh no, I cannot read this. Please, generate a