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?

6
  • I am sure your last while loop should generate exception... Commented Feb 1, 2015 at 7:37
  • @almasshaikh.. while loop does. My question was why isn't the for:each loop? It inherently uses Iterator() so, I should get an exception there too.. why isn't it happening? Commented Feb 1, 2015 at 7:38
  • Interesting. If you comment out the for loop, the while loop doesn't throw an exception. Commented Feb 1, 2015 at 7:41
  • What if you add Zeta and in your if you say treeSet.add("Meta"); See how scenario changes Commented Feb 1, 2015 at 7:44
  • @Eran.. see JB's answer.. it explains why.. Commented Feb 1, 2015 at 7:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.