Core Java Tutorials


Introduction

Java Hello World

Java Compilation

JDK New Features

JVM Architecture

Java OOPs Concepts

Java Package

Array

Exception Handling

String

Immutable Class

File Handling

Serialization

MultiThreading

Volatile

Concurrent Package

Collection

Collection Internal

Generics

Cloning

Reflection In Java

Annotation

Class Loader

Java Inner classes

Garbage Collector

JDBC

References In Java

Heap Dump & Thread Dump

fail-fast Iterator and fail-safe Iterator in Java

Iterators are used in collection to traverse over the Collection objects. Iterators returned by the Collection are either fail-fast in nature or fail-safe in nature. Fail-Fast iterators immediately throw ConcurrentModificationException if a collection is structurally modified while iterating over it.
 The iterators returned by HashMap,Hashtable,Vector,ArrayList,HashSet etc class's iterator() iterator are fail-fast.

Fail-Safe iterators don't throw any exceptions if a collection is structurally modified while iterating over it. Because, they operate on the clone of the collection, not on the actual collection.
 The iterators returned by CopyOnWriteArrayList,ConcurrentHashMap class's iterator() iterator are fail-safe.

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.The iterator will not reflect additions, removals, or changes to the list since the iterator was created.

 How ConcurrentModificationException works?

In Collection Framework to know whether the collection is modified or not during iterating it, Collection Framework uses an internal flag called modCount which is updated each time a collection is modified. Every time when an Iterator calls the next() method, it checks the modCount. If it finds the modCount has been updated after this Iterator has been created, it throws ConcurrentModificationException.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

 Picture representation of fail-fast & fail-safe

 The Enumeration returned by the elements() elements method are not fail-fast.

Example of fail-fast iterator.

import java.util.*;
public class ArrayListDemo {
	public static void main(String[] args) {
		// Generic Declaration
		List list = new ArrayList<String>(); //10
		list.add("Apple");
		list.add("Mango");
		list.add("Orange");
		list.add("Banana");
		list.add("Papaya");
		Iterator it = list.iterator();
		//Iterator can be used to access any collection which 
		//implements Iterable interface
		while (it.hasNext()) {
			//ConcurrentModificationException 
			list.add("Mocha");
			String element = it.next();
			System.out.println(element);
		}
	}	
}
 output:-
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
	at java.util.ArrayList$Itr.next(Unknown Source)
	at ArrayListDemo.main(ArrayListDemo.java:17)

Example of fail-safe iterator.

import java.util.*;
public class ArrayListDemo {
	public static void main(String[] args) {
		// Generic Declaration
		ConcurrentHashMap roleNames = 
				new ConcurrentHashMap();

		roleNames.put("1000", "Amit");
		roleNames.put("2000", "Rock");
		roleNames.put("3000", "Jhon");
		roleNames.put("4000", "Mike");
		
		Iterator iterator = roleNames.keySet().iterator();
		while (iterator.hasNext()) {
		String roll=iterator.next();
		System.out.println(roleNames.get(roll));
		//adding another entry during accessing the elements
		roleNames.put("5000", "Rajiya");
	  }
	}	
}
 output:-
Amit
Rock
Jhon
Rajiya
Mike
 Iterator can be used to access any collection which implements Iterable interface.