English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

The difference between fault fast and fault safe in Java

Serial numberKeyUnsatisfactoryFault-tolerant
1
Exception
Any changes to the collection (such as adding, deleting, and updating the collection during a thread) will fail when iterating over the collection and then quickly throw a concurrent modification exception. 
Fault-tolerant collections do not throw exceptions. 
2.
Collection types
ArrayList and hashmap collections are examples of quick-failure iterators 
CopyOnWrite and concurrent modification are examples of fault-tolerant iterators 
3.
Performance and memory
but works on the actual set. Therefore, this iterator does not require additional memory or time 
It is processing a clone of the set, not the actual set. There is an overhead in terms of time and memory
4.
Modification item
 Iterators do not allow modification of the set while iterating over it.
Fail-safe iterators allow modifications to be made to the collection while iterating over it.

Fail-Fast Example

public class FailSafeExample{
   public static void main(String[] args){
      ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
      //Add elements to the map
      map.put("Dell", 1;
      map.put("IBM", 2;
      //Get iterator from the map
      Iterator<String> it = map.keySet().iterator();
      while (it.hasNext()){
      String key = (String) it.next();
         System.out.println(key+" : "+map.get(key));
         map.put("Google", 3;
      }
   }
}

Output Result

IBM :2
Dell:1

Fail-Fast Example

public class FailFastExample{
   public static void main(String[] args){
      List<Integer> list = new ArrayList<Integer>();
      list.add(1;
      list.add(2;
      list.add(3;
      //Get iterator from the list
      Iterator<Integer> it = list.iterator();
      while (it.hasNext()){
         Integer integer = (Integer) it.next();
         list.add(4;
      }
   }
}

Output Result

Exception in thread "main" java.util.ConcurrentModificationException
   at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
You May Also Like