Collection throws or doesn’t throw ConcurrentModificationException based on the contents of the Collection [duplicate]

Short answer Because the fail-fast behavior of an iterator isn’t guaranteed. Long answer You’re getting this exception because you cannot manipulate a collection while iterating over it, except through the iterator. Bad: // we’re using iterator for (Iterator<String> i = c.iterator(); i.hasNext();) { // here, the collection will check it hasn’t been modified (in effort … Read more

Why isn’t this code causing a ConcurrentModificationException? [duplicate]

According to the Java API docs Iterator.hasNext does not throw a ConcurrentModificationException. After checking “January” and “February” you remove one element from the list. Calling it.hasNext() does not throw a ConcurrentModificationException but returns false. Thus your code exits cleanly. The last String however is never checked. If you add “April” to the list you get … Read more

Concurrent Modification exception [duplicate]

To avoid the ConcurrentModificationException, you should write your code like this: import java.util.*; public class SomeClass { public static void main(String[] args) { List<String> s = new ArrayList<String>(); for(String a : args) s.add(a); ListIterator<String> it = s.listIterator(); if(it.hasNext()) { String item = it.next(); } System.out.println(s); } } A java.util.ListIterator allows you to modify a list … Read more

Why am I not getting a java.util.ConcurrentModificationException in this example?

Here’s why: As it is says in the Javadoc: The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. This check … Read more

Why is a ConcurrentModificationException thrown and how to debug it

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself. Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Entry item = it.next(); map.remove(item.getKey()); } This will throw a ConcurrentModificationException when the it.hasNext() is called the second time. The correct … Read more