A java.util.ConcurrentModificationException costuma surpreender a muitos: como uma exception com esse nome pode aparecer mesmo em uma aplicação single threaded, que não envolve concorrência alguma no acesso dessa coleção??
Single Threaded no que se refere á programações multiplas , por exemplo um Handling database connections using SingleThreadModel , o mais curioso é porque fez observação para coleções ?
Sim, é uma concorrencia que poderiamos observar em outras situações como pertinentes a banco de dados envolvendo persistencia.
Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$ValueIterator.next(Unknown Source)
at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:555)
This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.
Iterator it = map.iterator();
while (it.hasNext())
{
Object item = it.next();
map.remove(item);
}
This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.
The correct approach would be
Iterator it = map.iterator();
while (it.hasNext())
{
Object item = it.next();
it.remove(item);
} Assuming this iterator supports the remove() operation.