Search code examples
javaandroiditeratorconcurrentmodification

Avoid ConcurrentModificationException using Iterator.next()


In my Android app I use this code while drawing some waypoints on a map

Iterator<Waypoint> iterator = waypoints.iterator();
while (iterator.hasNext()) {
   Waypoint w = iterator.next();
}

But I am getting this error

Fatal Exception: java.util.ConcurrentModificationException java.util.ArrayList$ArrayListIterator.next (ArrayList.java:573)

I am not modifying the list directly in the loop I am iterating over.

But it is possible that I modify the list in another thread because a user can move some waypoints. And the drawing of a waypoint can happen the same time a user uses the touch display to move a waypoint.

Can I avoid that exception somehow?


Solution

  • If you want to maintain a List you use in several threads, it's best you use a concurrent list, such as CopyOnWriteArrayList.

    Locally, you can avoid the exception by creating a copy of the waypoints list first and iterate that:

    Iterator<Waypoint> iterator = new ArrayList<>(waypoints).iterator();
    while (iterator.hasNext()) {
        handle(iterator.next());
    }