Java集合-05fail-fast(快速失败)机制原理及解决方法

 

fail-fast简介

fail-fast(快速失败),是Java集合的一种错误检测机制。当在遍历集合的过程中该集合在结构(改变集合大小)上发生变化时候,
有可能发生fail-fast,抛出java.util.ConcurrentModificationException异常。

fail-fast出现场景

  • 单线程场景
    •     public class FailFastSingleThreadTest {         public static void main(String[] args) {             List<String> lists = new ArrayList<>(10);             for (int i = 0; i < 4; i++){                 lists.add(String.valueOf(i));             }              //fail-fast             for (String list : lists) {                 lists.remove(3);             }         }     } //output:Exception in thread "main" java.util.ConcurrentModificationException
  • 多线程场景
    •   public class FailFastMultiThread  {       private static List<String> lists = new ArrayList<>(10);       static {           for (int i = 0; i < 4; i++){               lists.add(String.valueOf(i));           }       }       public static void main(String[] args) {           new Thread(new ForEachThread()).start();           new Thread(new EditThread()).start();       }        //用于遍历       static class ForEachThread implements Runnable{           @Override           public void run() {               Iterator<String> iterator = lists.iterator();               while (iterator.hasNext()){                   System.out.println(iterator.next());                   try {                       Thread.sleep(100);//为了另外的线程加入,也是为了结合在遍历时候修改结构                   } catch (InterruptedException e) {                       e.printStackTrace();                   }               }            }       }        //用于修改结构       static class EditThread implements Runnable{           @Override           public void run() {               lists.add("8");           }       }    }   //output:Exception in thread "Thread-0" java.util.ConcurrentModificationException

      产生原因

      集合能够遍历是因为迭代器的原因,而Iterator接口只是定义了具体的方法,集合需要实现该接口方法,
      查看ArrayList中具体的实现方法

        //省略部分方法   private class Itr implements Iterator<E> {       int cursor;       // index of next element to return       int lastRet = -1; // index of last element returned; -1 if no such       int expectedModCount = modCount;        
                              
      关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信