2

I have below codes and i would expect from case 2 scenario to throw ConcurrentModificationException ,but it runs successfully. As I know If i do the same thing with single key in map it does not throw exception because here but again when I am reproducing this scenario having multiple keys with two cases -

  1. modification by new key.
  2. modification by existing key.

Case 1:

    Map<String,String> mp = new HashMap<String,String>();
    mp.put("1", "10");
    mp.put("2", "11");
    mp.put("3", "12");
    mp.put("4", "13");

    for (String key :mp.keySet()) {
        mp.put("5", "14");
    }

This will work as expected , throws ConcurrentModificationException.

Case 2:

    Map<String,String> mp = new HashMap<String,String>();
    mp.put("1", "10");
    mp.put("2", "11");
    mp.put("3", "12");
    mp.put("4", "13");

    for (String key :mp.keySet()) {
        mp.put(key, "14");
    }

It will not throws ConcurrentModificationException. Why ??

Community
  • 1
  • 1
Alok Pathak
  • 875
  • 1
  • 8
  • 20

3 Answers3

4

In first case you are modifying the structure of the map so you get CME (adding a new key / value pair). In the second case you are not modifying the structure (overwriting values for existing keys). so you won't get CME

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

ConcurrentModificationException is thrown when its structure gets changed while iterating over it but in second case there is no change in structure . It means there is just update for existing key in map (neither addition or deletion in second case which would have caused change in structure)

See http://javahungry.blogspot.com/2014/04/fail-fast-iterator-vs-fail-safe-iterator-difference-with-example-in-java.html

M Sach
  • 33,416
  • 76
  • 221
  • 314
1

You can refer to the javadoc:

The iterators [...] 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.

And the definition of structural modification can be found there too:

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

Finally, it is worth also reading the last paragraph:

Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

assylias
  • 321,522
  • 82
  • 660
  • 783