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?

Chanikag
  • 1,419
  • 2
  • 18
  • 31

1 Answers1

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:

Community
  • 1
  • 1
bsiamionau
  • 8,099
  • 4
  • 46
  • 73