Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
juergen d Avatar asked Mar 10 '18 12:03

juergen d


People also ask

Does iterator avoid ConcurrentModificationException?

To Avoid ConcurrentModificationException in single-threaded environment. You can use the iterator remove() function to remove the object from underlying collection object. But in this case, you can remove the same object and not any other object from the list.

How many ways we can avoid 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.

What is ConcurrentModificationException and how it can be prevented?

The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes. For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it.


1 Answers

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());
}
like image 99
daniu Avatar answered Sep 28 '22 09:09

daniu