Avoiding TreeMap ConcurrentModificationException?

Note that Collections.synchronizedMap will never protect you from concurrent modification if you're using an iterator. In addition, unless you're accessing your Map from more than one thread, creating the synchronized map is useless. Locally-scoped collections and variables that are not being handed to other threads do not need to be synchronized.

My guess is that in the code you left out, you're iterating over one of Map.entrySet, Map.keySet, or Map.values, and calling put during that iteration (within the for loop). With the code you've shown, this is the only way this could happen.


If you use a ConcurrentSkipListMap is can be faster and doesn't have this issue.

public NavigableMap<String, String> function1() {
    NavigableMap<String, String> key_values = new ConcurrentSkipListMap<String, String>();
    // all key_values.put() goes here

    return key_values;
}

If you don't need the keys to be sorted you can use a ConcurrentHashMap.


You appear to be getting a synchronized map of a synchronized map. If I replace the call to function1() with a it's contents (simplified) we have:

Map<String, String> key_values =Collections.synchronizedMap(Collections.synchronizedMap( new TreeMap<String, String>()));

I think your calling line should be changed to:

Map<String, String> key_values = Classname.function1();