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?
How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.
Synchronized HashMap allows one null key and any number of null values. Iterators returned by Hashtable are fail-safe in nature. i.e they don't throw ConcurrentModificationException if the map is modified after the creation of the iterator. Iterators returned by synchronized HashMap are fail-fast in nature.
What Causes ConcurrentModificationException. The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With