What do you understand by iterator fail-fast property

What do you understand by iterator fail-fast property

Answer : Java Iterator is fail fast by design and it’s sole purpose is to iterate a collection in forward direction only. It checks the failure condition aggressively and throw “java.util.ConcurrentModificationException” if during iteration collection been modified before more damage happens.

Note: All collection classes in java.util package are fail fast and java.util.concurrent package are fail safe.

Fail fast algorithm is implemented using a volatile counter on the list object:

  • Whenever iterator is created the current value of the counter will be added to the iterator object
  • If list is update then counter will be incremented
  • During iteration operation method compares two counter values and throw exception

Please example below:

package com.javahonk.iteratortest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FailFastTest {

	public static void main(String[] args) {

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

	arrayList.add("Java");
	arrayList.add("Honk");

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

	// if modification done once we got iterator
	// object will throw CME exception
	arrayList.add("fail fast");
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);

	}

	//Below is definitely fail
	/*while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);
		arrayList.add("fail fast");

	}*/

	}

}

 

Output:

What do you understand by iterator fail-fast property

Leave a Reply

Your email address will not be published. Required fields are marked *