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?