2

ConcurrencyTest.java

    Set<String> treeSet = new TreeSet<String>();
    treeSet.add("Alpha");
    treeSet.add("Beta");
    treeSet.add("Gamma");
    treeSet.add("Delta");
    treeSet.add("Epsilon");

    for(String str : treeSet) {
        if("Gamma".equals(str)) {
            treeSet.add("Zeta");
        }
    }

    Iterator<String> it = treeSet.iterator();

    while(it.hasNext()){
        if("Gamma".equals(it.next())) {
            treeSet.add("Lambda");
        }
    }

Since Java's collection framework is fail-fast and for-each is just a wrapper around the Iterator, I was expecting a ConcurrentModificationException in both the for loop and also the while loop. But for some reason, the for loop executes perfectly and the new element is added to the set. So, what's going on there? Why wasn't I getting the exception?

Farvardin
  • 5,336
  • 5
  • 33
  • 54
RKodakandla
  • 3,318
  • 13
  • 59
  • 79

1 Answers1

3

Gamma is the last element in the iteration. So the iterator stops iterating after Gamma is reached, and so it can't detect that an element has been added during the iteration.

In the second loop, Gamma is not the last element anymore, since Zeta has been added. So once the iterator tries to reach Zeta, it throws the exception.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255