Search code examples
javahashmapconcurrentmodification

issue with hashmap getting concurrent modification exception


I am getting the below error while using map and performing some remove.How to avoid this ?

Caused by: java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$EntryIterator.next(HashMap.java:834)
    at java.util.HashMap$EntryIterator.next(HashMap.java:832)


   Map<FormField, Object> ItemMap = domainItem.getValues();         
   for (Map.Entry<FormField, Object> ValMap : ItemMap.entrySet()) {         
       List<Field> groupIdList = Mapper.getGroupId(groupFieldId);           
       for (Field field : groupIdList) {
           ItemMap.put(new FormField(field), domainItem.getDomainItemLinkId());
       }
       ItemMap.remove(ValMap.getKey());
   }

Solution

  • Update:

    Use Iterator and ConcurrentHashMap to avoid this scenario

    Following won't throw exception

        Map<Integer, String> map = new ConcurrentHashMap<Integer, String>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        for (Iterator<Integer> keys = map.keySet().iterator(); keys.hasNext();) {
            Integer key = keys.next();
            String val = map.get(key);
            map.remove(key);
        }
    

    or use another map while iterating and at the end copy it to source

    for example:

        Map<Integer, String> dummy = new HashMap<Integer, String>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        map.put(4, "d");
        dummy.putAll(map);
        for (Iterator<Integer> keys = dummy.keySet().iterator(); keys.hasNext();) {
            Integer key = keys.next();
            String val = map.get(key);
            map.remove(key);
        }
        System.out.println(map);