15

I'm using Vector instead of ArrayList to make a list safe in multi-threaded enviroment. But I keep getting ConcurrentModificationException when I trying to add items to the Vector while iterating it. Why is that and how can I prevent it?

1
  • 2
    concurrent != parallel. You can get a ConcurrentModificationException with a single thread.
    – John Vint
    Mar 15, 2013 at 16:58

3 Answers 3

9

You cannot modify a Vector while iterating over it. Store the items to add in a separate vector, and move them to the Vector when the loop is finished or loop over a copy of the original Vector.

ADDED: To get a mutex around the Vector in java, do this in both functions:

synchronized (list) {
  // modifying list
}

and:

synchronized (list) {
  // iterating over list
}

Of course I've assumed that the list is named list

11
  • 4
    Side note: this holds true even in single-threaded programs.
    – svckr
    Mar 15, 2013 at 16:50
  • what do you mean it holds true in single-threaded programs?
    – Shelef
    Mar 15, 2013 at 16:55
  • 1
    You can never modify the list while iterating over it. Even in single threaded programs. Modifying the underlying list invalidates the iterator.
    – fredrik
    Mar 15, 2013 at 16:56
  • so what the purpose of synchronized collections in this case?
    – Shelef
    Mar 15, 2013 at 16:57
  • 1
    @assylias That is not what that class does. It copies the list, throwing away the old one. What I propose is to wait with appending new items until the iterator finished.
    – fredrik
    Mar 15, 2013 at 17:04
2

if you want to add items as you iterate, you'll want to use a ListIterator. by using Vector, you're not bypassing this rule (obviously), so I would recommend using the ArrayList instead.

2
  • I don't think it is safe to add while iterating with a ListIterator if more than one thread is involved.
    – assylias
    Mar 15, 2013 at 16:58
  • 1
    @assylias, I misunderstood the question, I suppose. I was just addressing the ConcurrentModificationException.
    – mre
    Mar 16, 2013 at 1:10
2

If you need to iterate and add concurrently to your list, you should use a concurrent list, such as CopyOnWriteArrayList. Note that if you write a lot to the list it will not be very efficient.

Otherwise, if you use a Vector or a synchronizedList, you need to hold the list's lock while iterating. That will prevent the exception but it will also prevent concurrency...

Not the answer you're looking for? Browse other questions tagged or ask your own question.