0

I executed the following code

Map<String, SyncPrimitive> syncPrimitives = new HashMap<String, SyncPrimitive>();

for (SyncPrimitive primitive : this.getSyncPrimitives()) {
         String groupId = primitive.getId();
         primitive.onConnect(groupId);
    }

Then I' getting the following exception

Error while calling watcher 
java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$KeyIterator.next(HashMap.java:828)

In the onConnect method the primitive oject is modified. How can I overcome this issue?

2
  • 1
    Show your onConnect method. Commented May 31, 2013 at 7:58
  • Map take <K,V> does this code compile ? Commented May 31, 2013 at 8:02

1 Answer 1

7

You could not modify collection during iteration it with for-each. If you want to modify it, use Iterator.

This kind of exceptions pretty clear described in documentation:

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

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.

See related questions:

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.