Search code examples
javamultithreadingiteratorconcurrentmodificationfail-fast

Multiple threads using iterator.remove() on a single collection returning fail-fast iterator


Oracle says

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Could this mean that even if multiple threads are iterating together over the same collection's fail-fast implementation's (Vector,Hashmap,ArrayList,HashSet) object carry out iterator.remove() there would be no ConcurrentModificationException thrown?


Solution

  • No. This tells you that only safe way to remove elements while iterating (in one thread) is to use iterator.remove. And if collection is accessed (iterated or modified) from other threads - sometime you will get exception, sometime not - in general behavior is not deterministic so you should avoid using it or relying on it.

    That being said - only exception to this are Concurrent collections.