Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does one loop throw a ConcurrentModificationException, while the other doesn't?

I've run into this while writing a Traveling Salesman program. For an inner loop, I tried a

for(Point x:ArrayList<Point>) {
// modify the iterator
}

but when adding another point to that list resulted in a ConcurrentModicationException being thrown.

However, when I changed the loop to

for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}

the loop ran fine without throwing an exception.

Both a for loops, so why does one throw an exception while the other does not?

like image 764
Jason Avatar asked Mar 07 '10 18:03

Jason


People also ask

How can you avoid ConcurrentModificationException while iterating a collection?

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.

What are some of the ways that a ConcurrentModificationException can occur?

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.

How do I fix ConcurrentModificationException in Java?

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.

What is ConcurrentModificationException and how it can be prevented?

ConcurrentModificationException is a predefined Exception in Java, which occurs while we are using Java Collections, i.e whenever we try to modify an object concurrently without permission ConcurrentModificationException occurs which is present in java. util package.


1 Answers

As others explained, the iterator detects modifications to the underlying collection, and that is a good thing since it is likely to cause unexpected behaviour.

Imagine this iterator-free code which modifies the collection:

for (int x = 0; list.size(); x++)
{
  obj = list.get(x);
  if (obj.isExpired())
  {
    list.remove(obj);
    // Oops! list.get(x) now points to some other object so if I 
    // increase x again before checking that object I will have 
    // skipped one item in the list
  }
}
like image 101
Martin Avatar answered Sep 22 '22 01:09

Martin