0
Sponsored Links


Ad by Google
This is one of the popular topic in concurrent environment, where concurrent modification occurs. So In this post, I am going to explain you what is Fail-Fast in java iteration with a simple example, and how to avoid fail-fast.
In my previous, post we have already seen an example of ArrayList and how to create our own arraylist in java and of course a detail comparison between ArrayList and LinkedList here.
What is Fail Fast - 
Fail - Fast, basically is an exception known as ConcurrentModificationException, an occurs as soon as collection's structure modifies during the iteration of collection elements except the iterators own method.
That means if a collection modifies during it's iteration except the iterator's remove() method, than it will throws ConcurrentModificationException. Let's see an example where an ArrayList is modifies during its iteration using collection's remove method.
FailFastExample .java, complete example to throw ConcurrentModificationException
package com.collection;

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

public class FailFastExample {
 private static List<String> listLanguages = new ArrayList<String>();
 static {
  listLanguages.add("Java");
  listLanguages.add("Scala");
  listLanguages.add("C++");
 }
 public static void main(String[] args) {
  Iterator<String> iterator = listLanguages.iterator();
  while (iterator.hasNext()) {
   String language = iterator.next();
   if (language.equalsIgnoreCase("java")) {
    listLanguages.remove(language);//Collection's remove method
   }
  }
  System.out.println("Final list size - " + listLanguages.size());

 }
}
OUTPUT :
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at com.collection.FailFastExample.main(FailFastExample.java:18)

Key Points :
The ConcurrentModificationException is thrown by next() method, in each and every iteration, it will check for the collection modification inside next() method. The next method will call checkForComodification method,
final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
If modCount and expectedModCount is not equal than, it will throws ConcurrentModificationException.
Sponsored Links

0 comments:

Post a Comment