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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP