Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I used synchronized list, and i still get ConcurrentModificationException [duplicate]

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?

like image 439
Shelef Avatar asked Mar 15 '13 16:03

Shelef


People also ask

How do you overcome ConcurrentModificationException?

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.

Does synchronized HashMap throws ConcurrentModificationException?

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?

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.


1 Answers

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

like image 170
fredrik Avatar answered Sep 17 '22 18:09

fredrik