Java 中快速失败和安全失败之间的区别

javaobject oriented programmingprogramming更新于 2024/5/2 15:40:17

Sr.号关键快速失败故障安全
1
异常
在迭代集合的线程中添加、移除和更新集合等任何集合更改,都会快速失败并发修改异常。
故障安全集合不会抛出异常。
2.
集合类型
ArrayList 和 hashmap 集合是快速失败迭代器的示例 
CopyOnWrite 和并发修改是故障安全迭代器的示例 
3.
性能和内存
它处理的是实际的集合。因此,此迭代器不需要额外的内存和时间 
它处理的是集合的克隆,而不是实际的集合。这在时间和内存方面是有开销的
4.
修改
 迭代器不允许在迭代集合时对其进行修改。
故障安全迭代器允许在迭代集合时对其进行修改。

故障安全示例

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

FailSafe 示例

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)

相关文章


有用资源