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

La differenza tra fault tolerance e fault safety in Java

NumberKeyFailingFault-tolerant
1
Exceptions
Any changes to the collection (such as adding, deleting, and updating the collection during a thread) are to iterate over the collection and then quickly throw a concurrent modification exception. 
Fault-tolerant collections do not cause exceptions. 
2.
Collection types
ArrayList and hashmap collections are examples of fast-failure iterators 
CopyOnWrite and concurrent modification are examples of fault-tolerant iterators 
3.
Performance and memory
Instead, it works on the actual collection. Therefore, this iterator does not require additional memory and time 
It is processing a clone of the collection rather than the actual collection. Time and memory overhead
4.
Modification item
 The iterator does not allow modification of the collection while iterating over it.
Fault-tolerant iterator allows for modification of the collection while iterating over it.

故障保护示例

public class FailSafeExample{
   public static void main(String[] args){
      ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
      //在映射上添加元素
      map.put("Dell", 1);
      map.put("IBM", 2);
      //从映射获取迭代器
      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);
      }
   }
}

输出结果

IBM :2
Dell:1

故障保护示例

public class FailFastExample{
   public static void main(String[] args){
      List<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(3);
      //从列表中获取迭代器
      Iterator<Integer> it = list.iterator();
      while (it.hasNext()){
         Integer integer = (Integer) it.next();
         list.add(4);
      }
   }
}

输出结果

Exception in thread "main" java.util.ConcurrentModificationException
   at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
Ti potrebbe interessare