Safe to modify the list while iterating — changes do not affect the iterator.
import java.util.concurrent.CopyOnWriteArrayList;
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("Java");
list.add("Python");
for (String lang : list) {
list.remove(lang); // ✅ No ConcurrentModificationException
}
System.out.println(list); // []
🔧 Internals:
On every add or remove, it creates a new copy of the internal array.
Iterators never throw ConcurrentModificationException.
Tradeoff: Very safe, but expensive for write-heavy use cases.
2. ✅ ConcurrentHashMap.keySet().iterator()
Also part of java.util.concurrent.
Its iterator is weakly consistent:
Doesn’t throw ConcurrentModificationException
Reflects some or all updates during iteration
import java.util.concurrent.ConcurrentHashMap;
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("A", 1);
map.put("B", 2);
for (String key : map.keySet()) {
map.put("C", 3); // ✅ Safe — no exception
System.out.println(key);
}
🔧 Internals:
Uses lock striping or CAS (compare-and-swap) for concurrency.
Provides a weakly consistent view of the map during iteration.
Perfect for high-performance concurrent read/write access.