When you Iterate a collection using Java 1.5 modern for loop and remove some element
concurrentmodifuicationexception is thrown.
But when I run follwoing code it does not throw any exception:
public static void main(String a []){
Set<String> strs = new HashSet<String>();
strs.add("one");
strs.add("two");
strs.add("three);
for(String str : strs){
if(str.equalsIgnoreCase("two"){
strs.remove(str);
}
}
}
Above code does not throw ConcurrentModificationException. But when I use any such for loop in my web application service method it always throws one. Why? I am sure no two threads are accessing the collection when it runs in service method So what causes the difference in two scenarios where it is thrown in one and not in the other?
I get a
ConcurrentModificationExceptionwhen running your code (after fixing the few typos).The only scenarios where you would not get a
ConcurrentModificationExceptionare: