Parallel modification Exception thrown .next from Iterator

Not sure what is wrong here:

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

    }

This code throws a ConcurrentModificationException in itr.next ();

Initializing an iterator private Iterator<Stock> itr=stockList.iterator();

Any ideas?

[The main code was copied directly from the professor’s slides]

+3
source share
3 answers

There are two reasons for this.

  • Another thread updates the inventory list directly or through its iterator
  • In the same stream, possibly inside this cycle, the list of stocks changes (see example below)

The codes below may throw a ConcurrentModificationException

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

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

        stockList.remove(0) //Causes ConcurrentModificationException 
    } 
+5
source

- ? , , , : () .

+1

, - .

javadoc:

, listIterator fail-fast: , , ConcurrentModificationException. , , , , .

0

Source: https://habr.com/ru/post/1732458/


All Articles