I try to understand the working of Concurrent modification exception in Java, Initially I tried Concurrent modification exception example with normal ArrayList and HashSet by removing elements while iterating, and then with help of CopyOnWriteArrayList & CopyOnWriteArraySet, I resolved the Concurrent modification exception, Everything works fine. But the problem is, when I implicitly make the set as synchronized with help of Collection.synchronized(set) method, still it throws the Concurrent modification exception. CopyOnWriteArrayList & CopyOnWriteArraySet both are synchronized classes,so it doesnt throw Concurrent modification exception. Collection.synchronized(set) also returns synchronized set, then why it throws the Concurrent modification exception.
Can anyone explain what is issue here?
Here is the sample program,

The "concurrent" in
ConcurrentModificationExceptionhas nothing to do with threads. In fact, if you concurrently modify a collection in the sense of 'change it from 2 threads simultaneously', you may get a ConcurrentModificationException, but you may not. The JVM has a lot of leeway.The problem is much, much simpler. You did the following:
iterator()from a list.This trivially causes CoModEx, every time:
Here the list is modified (
list.remove(item)) after an iterator is made (for ( x : y)makes an iterator), and then after the modification, the iterator is interacted with (looping that for loop iteracts with it).Think about it: What does this even mean - what if the change you make affects something you haven't looped over yet. Do you expect the loop to still cover it, or not, or should it depend on where we are in the iteration? These are tricky questions. That's why the answer is 'nope, exception instead'.
So, what do you do?
CopyOnWriteArrayList. Which is probably overkill. These more or less let you iterate a copy.for (String x : y), create alistIteratorobject and use that. Then, to modify the list, call methods onlistIteratorto modify it, which is fine.