1

I'm getting a "An exception occurred: java.util.ConcurrentModificationException" when I run this piece of code. Does anyone here see what the problem is?

public void mudaDeEstado() {
    Luz luz = new Luz();
    while(this.iterador.hasNext()) {
        luz = (this.iterador.next());
        luz.defineEstado(!luz.acesa());
    }

}

Thanks a lot!!

1

2 Answers 2

7

You are trying to modify the reference that the iterator holds while looping through the elements. You can read more about his exception here.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Most probably the culprit here is this:

luz.defineEstado(!luz.acesa());
Sign up to request clarification or add additional context in comments.

2 Comments

It looks like the Iterator is set to iterador so there's potential for something happening between that being set and this method being called.
Yup - that could be it too. Hard to tell for sure without a stack trace and a complete code example.
2

This exception is thrown when you modify a data structure while you are iterating through it. Changing the elements in the data structure can change the way one iterates through the elements, so many data structures do not allow concurrent modification.

Try keeping a list of elements that need to be updated and then go back through and update those elements once you have iterated through the entire data structure.

Sorry my wording is kind of general and ambiguous, but it's hard to give specifics with the provided code.

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.