fail-safe机制和fail-fast机制的区别

147 阅读1分钟

最近在准备面试,看了一个up主的视频,想做个总结,

  1. up主的video:www.bilibili.com/video/BV1SL…

  2. 针对视频当中的exception,我做个总结

相同点

```
    他们都是多线程并发操作集合时的一种失败处理机制
```

不同点

fail-fast

    fail-fast表示快速失败,在集合的遍历数据过程中,一旦发现容器中的数据被修改过了,就会立刻抛出一个异
    常叫做ConcurrentModificationException,从而导致整个遍历过程是失败的,java.util包下的集合类都
    是属于快速失败机制的,有hashmap和arraylist
    
    
 
/**
 * @description:  演示快速失败的案例
 *                  Exception in thread "main" java.util.ConcurrentModificationException
 * @author: Ding Yawu
 * @create: 2022/3/5 23:10
 */
public class TestFailFast {
  public static void main(String[] args) {
      HashMap map = new HashMap<Integer,String>();
      map.put(1, "jack");
      map.put(2, "jack");
      map.put(3, "tom");
      map.put(4, "jack");
      map.put(5, "sam");
      Iterator iterator = map.keySet().iterator();
      while (iterator.hasNext()){
          System.out.println(map.get(iterator.next()));
          map.put(6, "lucy");
      }
  }
}

fail-safe


fail-safe表示一个失败安全机制,在遍历集合的情况下不会出现异常,采用失败安全机制的容器在遍历的时候,不是
直接在集合内容上进行访问,而是先复制原有集合的内容,在拷贝的集合上去遍历,这样的话迭代器是对原始集合的拷
贝去进行遍历访问的,所以在遍历过程中,对原始集合的修改并不能被迭代器检测到,java.util.concurrent包下
的容器都是属于失败安全的,有concurrentHashMap和CopyOnWriteArrayList
/**
 * @description: 失败安全机制的演示
 * 1
 * 2
 * 3
 * [1, 2, 3, 14]
 * @author: Ding Yawu
 * @create: 2022/3/5 23:21
 */
public class TestFailSafe {
  public static void main(String[] args) {
      CopyOnWriteArrayList<Integer> arrayList
              = new CopyOnWriteArrayList<>(new Integer[]{1, 2, 3});
      Iterator<Integer> iterator = arrayList.iterator();
      while (iterator.hasNext()){
          Integer tmp = iterator.next();
          System.out.println(tmp);
          if (Objects.equals(tmp, 2)){
              arrayList.add(14);
          }
      }
      System.out.println(arrayList);

  }
}