Java : ConcurrentModificationException while iterating over list

A synchronized List will does not provide a new implementation of Iterator. It will use the implementation of the synchronized list. The implementation of iterator() is:

public Iterator<E> iterator() {
   return c.iterator(); // Must be manually synched by user! 
}

From ArrayList:

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

From ConcurrentLinkedQueue#iterator:

Returns an iterator over the elements in this queue in proper sequence. The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

The iterators returned by the two collections are different by design.


don't do

myCollection.remove(myObject); 

do

it.remove();

There is no need for synchronization or concurrent collection


How is ConcurrentLinkedQueue in java.util.concurrent different from Collections.synchronizedList?

They have different implementations, and therefore may choose whether to throw ConcurrentModificationException, or to handle the situation you describe gracefully. Evidently CLQ handles gracefully, and ArrayList wrapped by Collections.synchronizedList (my guess is the behavior is ArrayList's, not the wrapper's) does not.

As @unbeli says, remove through the iterator, not the collection while iterating.