Java中快速失敗與安全失敗的區別


序號關鍵點快速失敗安全失敗
1
異常
在迭代器遍歷集合期間,如果對集合進行任何更改,例如新增、刪除和更新,則快速失敗迭代器會丟擲併發修改異常。
安全失敗集合不會丟擲異常。
2.
集合型別
ArrayList和HashMap集合是快速失敗迭代器的示例
CopyOnWrite和併發修改是安全失敗迭代器的示例
3.
效能和記憶體
它直接操作實際集合。因此,這種迭代器不需要額外的記憶體和時間。
它操作集合的副本而不是實際集合。在時間和記憶體方面存在開銷。
4.
修改
迭代器不允許在迭代過程中修改集合。
安全失敗迭代器允許在迭代過程中修改集合。

安全失敗示例

public class FailSafeExample{
   public static void main(String[] args){
      ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
      //Adding elements to map
      map.put("Dell", 1);
      map.put("IBM", 2);
      //Getting an Iterator from 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);
      }
   }
}

輸出

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);
      //Getting an Iterator from list
      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)

更新於:2019年11月18日

3K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.