This question already has an answer here:
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?
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...
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:
and:
Of course I've assumed that the list is named
list
if you want to add items as you iterate, you'll want to use a
ListIterator
. by usingVector
, you're not bypassing this rule (obviously), so I would recommend using theArrayList
instead.