I've run into a seemingly simple problem relating to deletion of objects in a collection I'm iterating through.
The setup is a very simple one-many, where the code below fails with a java.util.ConcurrentModificationException.
Code:
Iterator childIterator = getChildren().iterator();
while (iter.hasNext()) {
((Child) iter.next()).delete(session);
}
The getChildren method returns a set of children which is being iterated through, and a method "delete" is called on each child. The delete method updates other objects and an index, and possibly the child deletes itself by calling session.delete(this)
Everything works fine aslong as there's only one child. :) But if there are more, and one of the children is deleted, the childIterator/childSet is changed, and and the following call to iter.next() fails with the above exception. This might be expected since I'm delete from the collection I'm working on, and I understand why this is a problem, I just hope there's an easy solution. :)
If I convert the Set to an array, and runs through that, everything works fine, but that seems a bit too ugly for my taste.
PS I know for sure that only one thread is modifying the collection.