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