enfany
enfany

Reputation: 895

ConcurrentModificationException when iterate through List

I have a private class variable, it's declared as

private List<String> list= new ArrayList<String>();

My application throws java.util.ConcurrentModificationException when multiple threads are trying to iterate through the list

for (Iterator i = list.iterator();  i.hasNext(); ){
    System.out.println(i.next()+"\n");
}

I'm looking for advises to avoid this issue with minimal changes. This class variable is shared and used by multiple methods in this class.

Upvotes: 1

Views: 196

Answers (3)

PatrykG
PatrykG

Reputation: 103

You can try CopyOnWriteList, JavaDocs say:

This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.

 List<String> list = new CopyOnWriteArrayList<>();

Upvotes: 1

M. Shaw
M. Shaw

Reputation: 1742

When you are using an iterator on a Collection, you must use iterator.remove() and not Collection.remove() to prevent the ConcurrentModificationException. However, if you have multiple threads you may need to use Collections.syncrhonizedList() as well.

From the Oracle Java Docs:

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

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

Since you have already a clue that, the list is going to be accessed by multiple thread, declare a thread safe List.

List<String> list= Collections.synchronizedList(new ArrayList<String>());

Upvotes: 0

Related Questions