HuntExams Academy logo
JavaAdvanced#collections

What is the difference between fail-fast and fail-safe iterators?

Answer

Fail-fast (ArrayList, HashMap) throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe (ConcurrentHashMap, CopyOnWriteArrayList) operate on a clone or snapshot and don't throw.

Example

List<Integer> l = new ArrayList<>(List.of(1,2,3));
for (int x : l) { l.remove(0); } // throws ConcurrentModificationException

Related Interview Questions

1
JavaIntermediate#java8#streams

Explain Java 8 Streams.

Open
2
JavaIntermediate#java8#lambda

What are lambda expressions?

Open
3
JavaIntermediate#java8

What is a functional interface?

Open