Fail-Fast vs Fail-Safe Iterator in Java with Examples

Fail-Fast and Fail-Safe iterators are among the most frequently asked Java Collections Framework interview topics. Many developers have encountered ConcurrentModificationException but do not fully understand why it occurs.

In this article, we will learn what Fail-Fast and Fail-Safe iterators are, how they work internally, their differences, and how to avoid ConcurrentModificationException in real-world applications.

What is an Iterator?

An Iterator is used to traverse elements stored in Java collections. It provides a standard way to access collection elements one by one.


List<String> technologies =
        new ArrayList<>();

technologies.add("Java");
technologies.add("Spring Boot");
technologies.add("Kafka");

Iterator<String> iterator =
        technologies.iterator();

while(iterator.hasNext()) {
    System.out.println(iterator.next());
}

Output


Java
Spring Boot
Kafka

What is a Fail-Fast Iterator?

Fail-Fast iterators immediately throw a ConcurrentModificationException if the collection is structurally modified while iterating.

Most collection classes provide Fail-Fast iterators.

  • ArrayList
  • HashMap
  • HashSet
  • LinkedList
  • TreeMap

Example of a Fail-Fast Iterator


List<String> list = new ArrayList<>();

list.add("Java");
list.add("Spring");
list.add("Kafka");

for(String technology : list) {

    if("Spring".equals(technology)) {
        list.remove(technology);
    }
}

Output


Exception in thread "main"
java.util.ConcurrentModificationException

The collection was modified while iteration was in progress. Therefore the iterator immediately failed.

Why Does ConcurrentModificationException Occur?

Most collection classes maintain an internal variable called modCount.

Whenever the collection structure changes, modCount is updated. The iterator stores the expected modification count when iteration begins.

During traversal:

  • If modCount equals expectedModCount, iteration continues.
  • If modCount changes unexpectedly, ConcurrentModificationException is thrown.

Simplified Internal Logic


if(modCount != expectedModCount) {
    throw new ConcurrentModificationException();
}

This mechanism helps detect accidental modifications.

Modifying Collection Correctly

Instead of modifying the collection directly, use Iterator.remove().


List<String> list = new ArrayList<>();

list.add("Java");
list.add("Spring");
list.add("Kafka");

Iterator<String> iterator =
        list.iterator();

while(iterator.hasNext()) {

    String value = iterator.next();

    if("Spring".equals(value)) {
        iterator.remove();
    }
}

System.out.println(list);

Output


[Java, Kafka]

This works correctly because the iterator is aware of the modification.

What is a Fail-Safe Iterator?

Fail-Safe iterators operate on a copy of the collection rather than the original collection.

Because iteration occurs on a separate copy, modifications to the original collection do not cause ConcurrentModificationException.

Example of Fail-Safe Iterator


ConcurrentHashMap<Integer, String> map =
        new ConcurrentHashMap<>();

map.put(1, "Java");
map.put(2, "Spring");

for(Integer key : map.keySet()) {

    map.put(3, "Kafka");

    System.out.println(key);
}

No ConcurrentModificationException is thrown.

Collections That Provide Fail-Safe Behaviour

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • CopyOnWriteArraySet

CopyOnWriteArrayList Example


CopyOnWriteArrayList<String> list =
        new CopyOnWriteArrayList<>();

list.add("Java");
list.add("Spring");

for(String value : list) {

    list.add("Kafka");

    System.out.println(value);
}

Iteration continues without throwing ConcurrentModificationException.

Fail-Fast vs Fail-Safe

Feature Fail-Fast Fail-Safe
Throws ConcurrentModificationException Yes No
Works On Original Collection Yes No
Works On Copy No Yes
Memory Usage Low Higher
Performance Faster Slightly Slower
Thread Safe No Generally Safer

Fail-Fast Collections


ArrayList
LinkedList
HashSet
TreeSet
HashMap
TreeMap
LinkedHashMap

Fail-Safe Collections


ConcurrentHashMap
CopyOnWriteArrayList
CopyOnWriteArraySet

Real World Example

Suppose an e-commerce application maintains active user sessions. Multiple threads may read and update session information simultaneously.

Using ConcurrentHashMap makes more sense because modifications can occur while iteration is in progress.





Common Interview Questions

What is ConcurrentModificationException?

It is an exception thrown when a collection is modified while a Fail-Fast iterator is traversing it.

Does Fail-Fast guarantee an exception every time?

No. It is a best-effort mechanism designed to detect accidental modifications.

Is ConcurrentHashMap Fail-Fast?

No. ConcurrentHashMap provides Fail-Safe behaviour.

Why is Fail-Safe called Fail-Safe?

Because it does not fail when the underlying collection is modified during iteration.

Best Practices

  • Do not modify collections directly during iteration.
  • Use Iterator.remove() when removal is required.
  • Use ConcurrentHashMap for concurrent access scenarios.
  • Use CopyOnWriteArrayList when reads greatly outnumber writes.
  • Understand iterator behaviour before using collections in multi-threaded environments.

Frequently Asked Questions (FAQ)

Can ArrayList throw ConcurrentModificationException?

Yes. ArrayList uses a Fail-Fast iterator.

Can ConcurrentHashMap throw ConcurrentModificationException?

Typically no. It provides Fail-Safe behaviour.

Which iterator should be used in multi-threaded applications?

Fail-Safe iterators are generally preferred in multi-threaded environments.

Is Iterator.remove() safe?

Yes. It updates the collection in a way that the iterator understands.

Conclusion

Understanding the difference between Fail-Fast and Fail-Safe iterators is essential for every Java developer. Fail-Fast iterators help detect unintended modifications, while Fail-Safe iterators support concurrent updates safely. Knowing when to use each approach can prevent runtime errors and improve application reliability.

Keywords

Fail Fast Iterator Java, Fail Safe Iterator Java, ConcurrentModificationException, Iterator Interview Questions, Java Collections Framework, ArrayList Iterator, ConcurrentHashMap Iterator, CopyOnWriteArrayList, Fail Fast vs Fail Safe, Java Multithreading Collections, Iterator remove Method, Concurrent Collections Java, Core Java Interview Questions, Collections Framework Tutorial, Java Iterator Examples

Fail-Fast vs Fail-Safe Iterator in Java with Examples Fail-Fast vs Fail-Safe Iterator in Java with Examples Reviewed by 13thGhost on 3:20 PM Rating: 5

No comments:

Recommended Posts

Powered by Blogger.