Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 767
rennekon Avatar asked Jun 16 '26 08:06

rennekon


1 Answers

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 
    } 
like image 180
PassionatedDeveloper Avatar answered Jun 18 '26 21:06

PassionatedDeveloper