[Yanel-dev] infinite loop because of ConcurrentModificationException

Michael Wechner michael.wechner at wyona.com
Fri Mar 21 11:12:34 CET 2014


Hi

I would like to share the following code with you, because it caused
blocked threads and it took quite some time
to find the actual cause:

Iterator iterator = LinkedList.iterator();
while (iterator.hasNext()) {
   try {
      item = iterator.next();
      .....
   } catch(Exception e)
      log.error(e, e); // Let's be fault tolerant .
   }
}

This caused an infinite loop when the LinkedList was modified by another
thread during the while loop
was iterating of this LinkedList, because next() threw
ConcurrentModificationException and hence the next()
was never really executed and hence hasNext() always returned true.

The simple solution was to use the try/catch outside of the while loop.

try {
   while (iterator.hasNex()) {
      item = iterator.next();
       ....
   }
} catch(Exception e) {
   log.error(e, e); // Let's be fault tolerant
}

Also we replaced the LinkedList by CopyOnWriteArrayList.

You might call me silly using the code above in the first place, but
s*** happens and can cause very annoying problems.
(btw, using Javamelody helped me also to find and solve the problem).

Cheers

Michael


More information about the Yanel-development mailing list