views:

218

answers:

3

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]

A: 

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.

Suraj Chandran
A: 

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.

bmargulies
+2  A: 

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 , may be inside this loop itself, the stockList is modified

The bellow codes could cause ConcurrentModificationException

 while(itr.hasNext()) 
    { 

        Stock temp =itr.next(); 

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

        stockList.remove(0) //Causes ConcurrentModificationException 




    } 
Sreejesh