Java.Collections.

🛡️ Fail-Safe Iterators — Real Examples

1. ✅ CopyOnWriteArrayList.iterator()

  • Part of the java.util.concurrent package.
  • Iterator works on a snapshot copy of the array.
  • 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.

3. ✅ ConcurrentSkipListSet.iterator() / ConcurrentSkipListMap.iterator()

  • These are sorted, thread-safe collections.
  • Iterators are fail-safe and weakly consistent like ConcurrentHashMap.
import java.util.concurrent.ConcurrentSkipListSet;

ConcurrentSkipListSet<String> set = new ConcurrentSkipListSet<>();
set.add("Alpha");
set.add("Beta");

for (String item : set) {
    set.add("Gamma"); // ✅ Safe, no crash
    System.out.println(item);
}

🔄 Key Traits of Fail-Safe Iterators

PropertyDescription
🛡️ No ExceptionsThey don’t throw ConcurrentModificationException
👀 Snapshot or Weak ViewThey either work on a copy (snapshot) or see some concurrent changes
🧵 Thread-SafeDesigned to be safe in multithreaded environments
⚠️ TradeoffMay be slower for writing, or may not show all updates during iteration
This entry was posted in Без рубрики. Bookmark the permalink.