I don't understand why I get a ConcurrentModificationException when I iterate through this multimap
.
I read the following entry, but I am not sure if I understood the whole thing.
I tried to add a synchronized block. But my doubt is what to synchronize with, and when.
The multimap
is a field and created like this :
private Multimap<GenericEvent, Command> eventMultiMap =
Multimaps.synchronizedMultimap(HashMultimap.<GenericEvent, Command> create());
and used like this :
eventMultiMap.put(event, command);
and like this ( I tried to synchronize this part on the map, but without success )
for (Entry<GenericEvent, Command> entry : eventMultiMap.entries()) {
if (entry.getValue().equals(command)) {
eventMultiMap.remove(entry.getKey(), entry.getValue());
nbRemoved++;
}
}
In java8 you can also use a lambda approach:
eventMultiMap.entries().removeIf(genericEventCommandEntry -> genericEventCommandEntry.getValue().equals(command));