Chirag
Chirag

Reputation: 658

Concurrent Modification exception when only values of Hashmap are modified

I have code like below, in which the inner loop modifies the Hashmap, but only in a way that no new keys are added or deleted, but only the values are updated. Does this qualifies as modification of a Hashmap, for Concurrent Modification Exception to be thrown ? In current tests that I have done, I haven't found any exception to be thrown though.

for(String variable:variableMap.descendingKeySet()) {
        for (String innerVariable : variableMap.keySet()) {
            variableMap.put(innerVariable, variableMap.get(innerVariable).replace("$" + variable, variableMap.get(variable)));
        }
    }

Upvotes: 1

Views: 46

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

See the Javadoc of HashMap:

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.

Now what is "structurally modified" ?

A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.

So, no, you won't get a ConcurrentModificationException if you only modify the value of the key.

Upvotes: 2

Related Questions