Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Wednesday, January 4, 2012

What Causes a ConcurrentModificationException?

In Java, a ConcurrentModificationException can occur when attempting to modify a Collections object (ex, java.util.List) outside of an Iterator.  The documentation points to threads as a possible cause, but you can get this exception even doing single-threaded programming.

The following code throws a ConcurrentModificationException despite being executed in a single thread.


List<String> mylist = new ArrayList<String>();
mylist.add("one");
Iterator<String> iterator = mylist.iterator();
while( iterator.hasNext() ) {
  iterator.next();
  mylist.remove(0);  // throws the exception
}

The remove() call on the mylist interferes with the iterator processing.  The correct way to remove an item while iterating is to use java.util.Iterator's remove() method (this is different than java.util.List.remove(int)).

If your maintaining an application and see this exception, chances are the bug is not as easy to detect as the preceding code block.  Look for all remove() calls and make sure that they are all called outside of an iterator (as in a for loop with an index) or within an iterator (using iterator.remove()).

IllegalStateException

A related error is an IllegalStateException.  This can occur if you don't advance the iterator after a remove().


iterator.next();
iterator.remove();
iterator.remove();  // will throw the error

Keep the iterator pointer current, operating one element at a time with next() or remove();

No comments:

Post a Comment