Fail-Fast Iteration Vs Fail-Safe Iteration in JAVA Collections.

Krosumlabs
3 min readMay 13, 2021

1. Introduction

In this article, we will discuss the different iterator behaviors in java.

2. Iterators in Action

Iterators in Java are mainly used to traverse through the collection elements. During traversal, we can perform any access kind of operations like searching, copying, accessing the value with its key etc. But operations that involves modification of collection like adding new values, deleting an item or updating the value for an already existing element may throw an exception depending upon the iterator the collection has implemented. The iterator implementations are categorized into two types

  1. Fail-fast iteration
  2. Fail-safe Iteration.

2.1. What is Fail-fast iteration ?

During traversal on the collection elements, If We try to modify the content of the same, then if that results in an exception, then it s said that the collection has implemented Fail-Fast Iteration.

Map<Integer, String> failFastMap = new HashMap<>();
// fail-fast Implementation
// Add elements to the map structure

for(Integer key : failFastMap.keySet()) {
failFastMap.remove(10);
}

The above code tries to create a Map defined with HashMap Implementation. Classes such as HashMap , ArrayList have Fail-Fast Iteration Implementation on their iterator behavior. Hence during traversal, failFastMap.remove(10) returns ConcurrentModificationException, not allowing us to perform further print statement execution. Such kind of collections are NOT Thread-Safe and are mostly preferred in sequential operations.

2.2. What is Fail-Safe Iteration ?

All Fail-Safe Implementations makes a cloned copy on the collection and traverses only on the cloned copy. Thus, as with our example, calling remove() method on collection modifies the original collection and not the cloned copy being traversing. Unlike, fail-fast iteration implementation, they are Thread-Safe and can be applied in Concurrent operations. But mostly, this Fail-Safe Implementation is not recommended for large collection as they consume large memory while making a clone. Also, their behavior is not predicted, that in some cases, they return inconsistent data.

Map <Integer, String> failSafeMap = new ConcurrentHashMap<>();
// fail-safe Implementation
// Add elements to map structure
for(Integer key : failSafeMap.keySet()) {
failSafeMap.remove(3);
}

3. Conclusion

As a conclusion, prefer Fail-Fast implementation for sequential operation involving large set of elements that restricts changes during traversal and Fail-Safe implementation in concurrent application with limited sized collection.

In this article, we have seen the definition of fail-Fast Iteration and Fail-Safe Iteration and its implementation. For full sourcecode, refer Krosumlab’s Github.

>>>> Check out the course

--

--

Krosumlabs

Technical Institution help you to master in PYTHON, RUBY, ANSIBLE, MACHINE LEARNING and BASH SCRIPTS.