0
List<ModelElement> elementList; //holds all model element
List<UUID> selectedElements;

public ModelElement getElement(UUID id)
{
    ModelElement element = null;
    for (ModelElement e : elementList){
        if (e.getId().equals(id) ){
            element = e;
            break;
        }
    }
    return element;
}

public void deleteElement(UUID id)
{
    selectedElements.remove(id);
    elementList.remove(getElement(id));
}

public void deleteElement(List<UUID> ids)
{
    for (UUID id : ids)
    {
        deleteElement(id);
    }

}

Why does this code create a java.util.ConcurrentModificationException? It works fine, if I call the single id version, but crashes if I use the List one.

5
  • We can't answer that either unless you post a complete, runnable program. You obviously have multiple threads somewhere, but this code shows nothing about what threads are using it. Commented May 19, 2015 at 16:06
  • Please provide an mcve Commented May 19, 2015 at 16:06
  • 1
    Are you passing selectedElements into the deleteElement call? A short but complete program demonstrating the problem would really help... Commented May 19, 2015 at 16:07
  • @Jon Skeet That was the the problem. The ids is the same reference as selectedElements. Commented May 19, 2015 at 16:10
  • 2
    Right. So that means you're iterating over something, and deleting from it within the for loop - that's why it fails. Commented May 19, 2015 at 16:12

1 Answer 1

2

To avoid CME, try using iterator if you want to call deleteElement() with selectedElements list:

public void deleteElement(List<UUID> ids)
{
    Iterator idIter = ids.iterator();
    while(idIter.hasNext())
    {
        UUID id = (UUID)idIter.next();
        elementList.remove(getElement(id));
        idIter.remove();            
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.