How an Iterator throws a ConcurrentModificationException when adding

Like Iteratorthrow ConcurrentModificationException, when we add some object after the current node or delete some object after the current node. Does it support a Iteratorcopy or link to the base collection?

+5
source share
5 answers

The iterator maintains a reference to the base collection. If you add or remove an item, the iterator may be left with an impossible index, or the collection may change the out-of-iterator.

Therefore, instead of letting the iterator get corrupted without telling you, most collections are courtesy of throwing a ConcurrentModificationException when trying to change the collection during iteration, so you don't end up with unpredictably distorted iterators.

+5
source

Under the contract, you are not allowed to modify the collection during iteration of it (with the exception of use Iterator.remove(), etc.).

Instead of accidentally crashing when you do this, the collection is good enough to keep track of how many times it has been modified, and toss ConcurrentModificationExceptionit when it detects a simultaneous modification.

+2
source

ConcurrentModificationException, , , . :

, Oracle, ConcurrentModificationException. ( ) , , , .

Oracle ( ) "" , java.util.concurrent(ConcurrentHashMap, ConcurrentLinkedQueue, ConcurrentSkipListMap ConcurrentSkipListSet). , , , . , , .

+1

iterator.remove(), :

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = iterator.next();
    /* ... */
    if (condition) {
       iterator.remove();
    }

To add, you can replace the simple Iterator for ListIterator as follows

ListIterator<Object> iterator = list.listIterator();
iterator.add(new Object());
+1
source

Of course, the iterator has a link to the base collection, this avoids copying. If you look at the example of the source code of the ArrayList (ListItr) iterator, you will see that there is basically a link to the list and cursor.

So, do not use an iterator between threads and do not modify the collection in which you iterate.

0
source

All Articles