简体   繁体   中英

Concurrent Modification Exception thrown by .next from Iterator

Not sure exactly what's wrong here:

    while(itr.hasNext())
    {
        Stock temp =itr.next();

    }

This code is throwing a ConcurrentModificationException at itr.next();

Initialization for the iterator is private Iterator<Stock> itr=stockList.iterator();

Any ideas?

[The basic code was copied directly from professor's slides]

This could be happening because of two reasons.

  1. Another thread is updating stockList either directly or through its iterator
  2. In the same thread, maybe inside this loop itself, the stockList is modified (see below for an example)

The below codes could cause ConcurrentModificationException

Iterator<Stock> itr = stockList.iterator();
 while(itr.hasNext()) 
    { 
        Stock temp = itr.next(); 

        stockList.add(new Stock()); // Causes ConcurrentModificationException 

        stockList.remove(0) //Causes ConcurrentModificationException 
    } 

Some other thread is modifying the underlying collection? I suspect that there is code above what you are showing us that causes the problem: a mod to the collection between the call to iterator() and the loop.

Most plausible reason is that some code has modified the underlying collection after you obtained your iterator.

Form 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. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM