user1363410
user1363410

Reputation: 135

how to fix ConcurrentModificationExceptions in multi-threaded environment?

This is the error I keep getting.

"Exception in thread "Thread-3" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:782)
at java.util.ArrayList$Itr.next(ArrayList.java:754)
at group1.bt.Announce.run(Announce.java:22)
at java.lang.Thread.run(Thread.java:679)"

Upvotes: 2

Views: 1347

Answers (3)

UVM
UVM

Reputation: 9914

You can use the following methods to avoid ConcurrentModificationException:

 ListIterator

    Synchronizers

    CopyOnWrite

    toArray()

    Concurrent Collections:

You can use ConcurrentHashMap from Concurrent Collection API in this case.I think this is easy and will not freeze object only for updation.

Upvotes: 0

Femi
Femi

Reputation: 64700

Your problem is that you are altering the underlying list from inside your iterator loop. You should show the code at line 22 of Announce.java so we can see what specifically you are doing wrong, but either copying your list before starting the loop, using a for loop instead of an iterator, or saving the items you want to remove from the list to a new list and then removing them en-masse after completing the iterator loop would work.

Upvotes: 3

Paul Vargas
Paul Vargas

Reputation: 42020

You need a synchronized view of your list.

List list = Collections.synchronizedList(new ArrayList());
   ...
synchronized (list) {
   Iterator i = list.iterator(); // Must be in synchronized block
   while (i.hasNext())
       foo(i.next());
}

Upvotes: 3

Related Questions