ToB企服应用市场:ToB评测及商务社交产业平台

标题: java中fail-fast和fail-safe的区别说明 [打印本页]

作者: 慢吞云雾缓吐愁    时间: 2022-8-20 18:39
标题: java中fail-fast和fail-safe的区别说明
转自:
  http://www.java265.com/JavaJingYan/202206/16540696313601.html
下文笔者讲述fail-fast和fail-safe的区别说明,如下所示同步修改简介说明
  1. 同步修改(并发修改)指:
  2. 当一个或多个线程正在遍历一个集合Collection
  3. 此时另一个线程修改了这个集合的内容(添加,删除或修改)
复制代码
fail-fast机制
  1. fail-fast机制:
  2.    在遍历一个集合时,当集合结构被修改,会抛出Concurrent Modification Exception
  3. fail-fast:
  4.     会在以下两种情况下抛出ConcurrentModificationException
  5.   1.单线程环境
  6.     集合被创建后,在遍历它的过程中修改了结构。
  7.    注意:
  8.      remove()方法会让expectModcount和modcount相等,所以是不会抛出这个异常
  9.   2.多线程环境
  10.     当一个线程在遍历这个集合,而另一个线程对这个集合的结构进行了修改
  11. 注意事项:
  12.    迭代器的快速失败行为无法得到保证,
  13.     因为一般来说,不可能对是否出现不同步并发修改做出任何硬性保证
  14.     快速失败迭代器会尽最大努力抛出 ConcurrentModificationException
  15.         因此,为提高这类迭代器的正确性而编写一个依赖于此异常的程序是错误的做法:迭代器的快速失败行为应该仅用于检测bug
复制代码
fail-fast机制检测方法分享
  1. 迭代器在遍历过程中是直接访问内部数据的
  2. 因此内部的数据在遍历的过程中无法被修改
  3. 为了保证不被修改,迭代器内部维护了一个标记"mode",
  4. 当集合结构改变(添加删除或者修改)
  5. 标记"mode"会被修改,而迭代器每次的hasNext()和next()方法都会检查该"mode"是否被改变
  6. 当检测到被修改时,抛出Concurrent Modification Exception
  7. 下面看看ArrayList迭代器部分的源码
  8. private class Itr implements Iterator<E> {
  9.         int cursor;
  10.         int lastRet = -1;
  11.         int expectedModCount = ArrayList.this.modCount;
  12.         public boolean hasNext() {
  13.             return (this.cursor != ArrayList.this.size);
  14.         }
  15.         public E next() {
  16.             checkForComodification();
  17.             /** 省略此处代码 */
  18.         }
  19.         public void remove() {
  20.             if (this.lastRet < 0)
  21.                 throw new IllegalStateException();
  22.             checkForComodification();
  23.             /** 省略此处代码 */
  24.         }
  25.         final void checkForComodification() {
  26.             if (ArrayList.this.modCount == this.expectedModCount)
  27.                 return;
  28.             throw new ConcurrentModificationException();
  29.         }
  30.     }
复制代码
fail-safe机制
  1. fail-safe任何对集合结构的修改都会在一个复制的集合上进行修改,因此不会抛出ConcurrentModificationException
  2. fail-safe机制有两个问题
  3.    1.需要复制集合,产生大量的无效对象,开销大
  4.    2.无法保证读取的数据是目前原始数据结构中的数据
复制代码
fail-fast和fail-safe示例
  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. public class FailFastExample
  5. {
  6.     public static void main(String[] args)
  7.     {
  8.         Map<String,String> map = new HashMap<String,String>();
  9.         map.put("test", "test");
  10.         map.put("test2", "test2");
  11.         map.put("test3","test3");
  12.         
  13.         Iterator iterator = map.keySet().iterator();
  14.         
  15.         while (iterator.hasNext())
  16.         {
  17.             System.out.println(map.get(iterator.next()));
  18.             map.put("test5", "test555");
  19.         }
  20.         
  21.     }
  22.    
  23. }
  24. -----运行以上代码,将输出以下信息-----
  25. Exception in thread "main" java.util.ConcurrentModificationException
  26.         at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
  27.         at java.util.HashMap$KeyIterator.next(Unknown Source)
  28.         at FailFastExample.main(FailFastExample.java:20)
  29. import java.util.concurrent.ConcurrentHashMap;
  30. import java.util.Iterator;
  31. public class FailSafeExample
  32. {
  33.     public static void main(String[] args)
  34.     {
  35.         ConcurrentHashMap<String,String> map =
  36.                                new ConcurrentHashMap<String,String>();
  37.         map.put("test", "test");
  38.         map.put("test2", "test2");
  39.         map.put("test3","test3");
  40.         
  41.         Iterator iterator = map.keySet().iterator();
  42.         
  43.         while (iterator.hasNext())
  44.         {
  45.             System.out.println(map.get(iterator.next()));
  46.             map.put("test5", "test5555");
  47.         }
  48.         
  49.     }
  50.    
  51. }
  52. 输出
  53. test
  54. test2
  55. test3
复制代码
fail-fast和fail-safe的区别

 Fail Fast IteratorFail Safe Iterator
Throw ConcurrentModification Exceptionyesno
Clone objectnoyes
Memory Overheadnoyes
HashMap,Vector,ArrayList,HashSetCopyOnWriteArrayList, ConcurrentHashMap
 


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4