2
Sponsored Links


Ad by Google
One of the popular java interview question just like why string is immutable in java and specially for beginners and most of them failed to explain what is difference between fail-fast and fail safe. I always ask this question from the below five years of candidate and some of them answered very well and some of them failed to explain. In this article, I am going to show you what is difference between fail fast and fail safe.
This question is also a starting point of concurrency discussion, if interviewer got the expected answered of this question then he/she start digging into more concurrency questions like BlockingQueue and Countdown latch etc.
What is fail fast
Fail fast is an ConcurrentModificationException and occurs as soon as collection's structure modifies internally while iterating  the collection's element except the iterators own method. Although fail fast behaviour of an iterator is not guaranteed.
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)

Here is a separate post on What is fail fast with code example.
What is fail safe
Fail safe does not throw ConcurrentModificationException because fail safe iterator works on clone copy of actual object instead of actual object, so doing any modification on clone copy will not impact on actual structure that's why it does not throws ConcurrentModificationException.
But it requires extra memory overhead to maintain the clone copy as well as it's not guarantee that the data being read is actually an original data.

Key points
  1. Fail fast throws ConcurrentModificationException whereas Fail safe does not.
  2. Fail fast works on actual object whereas Fail safe works on clone copy of object.
  3. Fail fast does not require extra memory overhead whereas Fail safe require extra memory overhead to maintain the clone copy of the data.
Sponsored Links

2 comments:

  1. subodh excellent explanation keep it up. vikas

    ReplyDelete
    Replies
    1. Thanks Vikash,Keep visiting definitely, you will find something useful to you.

      Delete