Java 集合系列 04 之 fail-fast 总结 (通过 ArrayList 来说明 fail-fast 的原理、解决办法)

Java 集合系列 04 之 fail-fast 总结 (通过 ArrayList 来说明 fail-fast 的原理、解决办法)

概要

前面,我们已经学习了 ArrayList。接下来,我们以 ArrayList 为例,对 Iterator 的 fail-fast 机制进行了解。内容包括::
1 fail-fast 简介
2 fail-fast 示例
3 fail-fast 解决办法
4 fail-fast 原理
5 解决 fail-fast 的原理

转载请注明出处:http://www.cnblogs.com/skywang12345/p/3308762.html

1 fail-fast 简介

fail-fast 机制是 java 集合 (Collection) 中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生 fail-fast 事件。
例如:当某一个线程 A 通过 iterator 去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程 A 访问集合时,就会抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

在详细介绍 fail-fast 机制的原理之前,先通过一个示例来认识 fail-fast。

2 fail-fast 示例

示例代码:(FastFailTest.java)

img

img

[img](javascript:void(0)😉

1 import java.util.*;
 2 import java.util.concurrent.*;
 4 /*
 5  * @desc java集合中Fast-Fail的测试程序。
 6  *
 7  *   fast-fail事件产生的条件:当多个线程对Collection进行操作时,若其中某一个线程通过iterator去遍历集合时,该集合的内容被其他线程所改变;则会抛出ConcurrentModificationException异常。
 8  *   fast-fail解决办法:通过util.concurrent集合包下的相应类去处理,则不会产生fast-fail事件。
 9  *
10  *   本例中,分别测试ArrayList和CopyOnWriteArrayList这两种情况。ArrayList会产生fast-fail事件,而CopyOnWriteArrayList不会产生fast-fail事件。
11  *   (01) 使用ArrayList时,会产生fast-fail事件,抛出ConcurrentModificationException异常;定义如下:
12  *            private static List<String> list = new ArrayList<String>();
13  *   (02) 使用时CopyOnWriteArrayList,不会产生fast-fail事件;定义如下:
14  *            private static List<String> list = new CopyOnWriteArrayList<String>();
15  *
16  * @author skywang
17  */
18 public class FastFailTest {
20     private static List<String> list = new ArrayList<String>();
21     //private static List<String> list = new CopyOnWriteArrayList<String>();
22     public static void main(String[] args) {
24         // 同时启动两个线程对list进行操作!
25         new ThreadOne().start();
26         new ThreadTwo().start();
27     }
29     private static void printAll() {
30         System.out.println("");
32         String value = null;
33         Iterator iter = list.iterator();
34         while(iter.hasNext()) {
35             value = (String)iter.next();
36             System.out.print(value+", ");
37         }
38     }
40     /**
41      * 向list中依次添加0,1,2,3,4,5,每添加一个数之后,就通过printAll()遍历整个list
42      */
43     private static class ThreadOne extends Thread {
44         public void run() {
45             int i = 0;
46             while (i<6) {
47                 list.add(String.valueOf(i));
48                 printAll();
49                 i++;
50             }
51         }
52     }
54     /**
55      * 向list中依次添加10,11,12,13,14,15,每添加一个数之后,就通过printAll()遍历整个list
56      */
57     private static class ThreadTwo extends Thread {
58         public void run() {
59             int i = 10;
60             while (i<16) {
61                 list.add(String.valueOf(i));
62                 printAll();
63                 i++;
64             }
65         }
66     }
68 }

[img](javascript:void(0)😉

View Code

运行结果
运行该代码,抛出异常 java.util.ConcurrentModificationException!即,产生 fail-fast 事件!

结果说明
(01) FastFailTest 中通过 new ThreadOne().start() 和 new ThreadTwo().start() 同时启动两个线程去操作 list。
ThreadOne 线程:向 list 中依次添加 0,1,2,3,4,5。每添加一个数之后,就通过 printAll() 遍历整个 list。
ThreadTwo 线程:向 list 中依次添加 10,11,12,13,14,15。每添加一个数之后,就通过 printAll() 遍历整个 list。
(02) 当某一个线程遍历 list 的过程中,list 的内容被另外一个线程所改变了;就会抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

3 fail-fast 解决办法

fail-fast 机制,是一种错误检测机制。它只能被用来检测错误,因为 JDK 并不保证 fail-fast 机制一定会发生。若在多线程环境下使用 fail-fast 机制的集合,建议使用 “java.util.concurrent 包下的类” 去取代“java.util 包下的类”。
所以,本例中只需要将 ArrayList 替换成 java.util.concurrent 包下对应的类即可。
即,将代码

private static List<String> list = new ArrayList<String>();

替换为

private static List<String> list = new CopyOnWriteArrayList<String>();

则可以解决该办法。

4 fail-fast 原理

产生 fail-fast 事件,是通过抛出 ConcurrentModificationException 异常来触发的。
那么,ArrayList 是如何抛出 ConcurrentModificationException 异常的呢?

我们知道,ConcurrentModificationException 是在操作 Iterator 时抛出的异常。我们先看看 Iterator 的源码。ArrayList 的 Iterator 是在父类 AbstractList.java 中实现的。代码如下:

img

img

[img](javascript:void(0)😉

1 package java.util;
 3 public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
 5     ...
 7     // AbstractList中唯一的属性
 8     // 用来记录List修改的次数:每修改一次(添加/删除等操作),将modCount+1
 9     protected transient int modCount = 0;
11     // 返回List对应迭代器。实际上,是返回Itr对象。
12     public Iterator<E> iterator() {
13         return new Itr();
14     }
16     // Itr是Iterator(迭代器)的实现类
17     private class Itr implements Iterator<E> {
18         int cursor = 0;
20         int lastRet = -1;
22         // 修改数的记录值。
23         // 每次新建Itr()对象时,都会保存新建该对象时对应的modCount;
24         // 以后每次遍历List中的元素的时候,都会比较expectedModCount和modCount是否相等;
25         // 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
26         int expectedModCount = modCount;
28         public boolean hasNext() {
29             return cursor != size();
30         }
32         public E next() {
33             // 获取下一个元素之前,都会判断“新建Itr对象时保存的modCount”和“当前的modCount”是否相等;
34             // 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
35             checkForComodification();
36             try {
37                 E next = get(cursor);
38                 lastRet = cursor++;
39                 return next;
40             } catch (IndexOutOfBoundsException e) {
41                 checkForComodification();
42                 throw new NoSuchElementException();
43             }
44         }
46         public void remove() {
47             if (lastRet == -1)
48                 throw new IllegalStateException();
49             checkForComodification();
51             try {
52                 AbstractList.this.remove(lastRet);
53                 if (lastRet < cursor)
54                     cursor--;
55                 lastRet = -1;
56                 expectedModCount = modCount;
57             } catch (IndexOutOfBoundsException e) {
58                 throw new ConcurrentModificationException();
59             }
60         }
62         final void checkForComodification() {
63             if (modCount != expectedModCount)
64                 throw new ConcurrentModificationException();
65         }
66     }
68     ...
69 }

[img](javascript:void(0)😉

View Code

从中,我们可以发现在调用 next() 和 remove() 时,都会执行 checkForComodification()。若 “modCount 不等于 expectedModCount”,则抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

要搞明白 fail-fast 机制,我们就要需要理解什么时候 “modCount 不等于 expectedModCount”!
从 Itr 类中,我们知道 expectedModCount 在创建 Itr 对象时,被赋值为 modCount。通过 Itr,我们知道:expectedModCount 不可能被修改为不等于 modCount。所以,需要考证的就是 modCount 何时会被修改。

接下来,我们查看 ArrayList 的源码,来看看 modCount 是如何被修改的。

img

img

[img](javascript:void(0)😉

1 package java.util;
  3 public class ArrayList<E> extends AbstractList<E>
  4         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  5 {
  7     ...
  9     // list中容量变化时,对应的同步函数
 10     public void ensureCapacity(int minCapacity) {
 11         modCount++;
 12         int oldCapacity = elementData.length;
 13         if (minCapacity > oldCapacity) {
 14             Object oldData[] = elementData;
 15             int newCapacity = (oldCapacity * 3)/2 + 1;
 16             if (newCapacity < minCapacity)
 17                 newCapacity = minCapacity;
 18             // minCapacity is usually close to size, so this is a win:
 19             elementData = Arrays.copyOf(elementData, newCapacity);
 20         }
 21     }
 24     // 添加元素到队列最后
 25     public boolean add(E e) {
 26         // 修改modCount
 27         ensureCapacity(size + 1);  // Increments modCount!!
 28         elementData[size++] = e;
 29         return true;
 30     }
 33     // 添加元素到指定的位置
 34     public void add(int index, E element) {
 35         if (index > size || index < 0)
 36             throw new IndexOutOfBoundsException(
 37             "Index: "+index+", Size: "+size);
 39         // 修改modCount
 40         ensureCapacity(size+1);  // Increments modCount!!
 41         System.arraycopy(elementData, index, elementData, index + 1,
 42              size - index);
 43         elementData[index] = element;
 44         size++;
 45     }
 47     // 添加集合
 48     public boolean addAll(Collection<? extends E> c) {
 49         Object[] a = c.toArray();
 50         int numNew = a.length;
 51         // 修改modCount
 52         ensureCapacity(size + numNew);  // Increments modCount
 53         System.arraycopy(a, 0, elementData, size, numNew);
 54         size += numNew;
 55         return numNew != 0;
 56     }
 59     // 删除指定位置的元素 
 60     public E remove(int index) {
 61         RangeCheck(index);
 63         // 修改modCount
 64         modCount++;
 65         E oldValue = (E) elementData[index];
 67         int numMoved = size - index - 1;
 68         if (numMoved > 0)
 69             System.arraycopy(elementData, index+1, elementData, index, numMoved);
 70         elementData[--size] = null; // Let gc do its work
 72         return oldValue;
 73     }
 76     // 快速删除指定位置的元素 
 77     private void fastRemove(int index) {
 79         // 修改modCount
 80         modCount++;
 81         int numMoved = size - index - 1;
 82         if (numMoved > 0)
 83             System.arraycopy(elementData, index+1, elementData, index,
 84                              numMoved);
 85         elementData[--size] = null; // Let gc do its work
 86     }
 88     // 清空集合
 89     public void clear() {
 90         // 修改modCount
 91         modCount++;
 93         // Let gc do its work
 94         for (int i = 0; i < size; i++)
 95             elementData[i] = null;
 97         size = 0;
 98     }
100     ...
101 }

[img](javascript:void(0)😉

View Code

从中,我们发现:无论是 add()、remove(),还是 clear(),只要涉及到修改集合中的元素个数时,都会改变 modCount 的值。

接下来,我们再系统的梳理一下 fail-fast 是怎么产生的。步骤如下:
(01) 新建了一个 ArrayList,名称为 arrayList。
(02) 向 arrayList 中添加内容。
(03) 新建一个 “线程 a”,并在 “线程 a” 中通过 Iterator 反复的读取 arrayList 的值
(04) 新建一个 “线程 b”,在 “线程 b” 中删除 arrayList 中的一个 “节点 A”。
(05) 这时,就会产生有趣的事件了。
在某一时刻,“线程 a”创建了 arrayList 的 Iterator。此时 “节点 A” 仍然存在于 arrayList 中,创建 arrayList 时,expectedModCount = modCount(假设它们此时的值为 N)。
在 “线程 a” 在遍历 arrayList 过程中的某一时刻,“线程 b”执行了,并且 “线程 b” 删除了 arrayList 中的 “节点 A”。“线程 b” 执行 remove()进行删除操作时,在 remove()中执行了“modCount++”,此时 modCount 变成了 N+1
“线程 a”接着遍历,当它执行到 next()函数时,调用 checkForComodification()比较 “expectedModCount” 和“modCount”的大小;而“expectedModCount=N”,“modCount=N+1”, 这样,便抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

至此,我们就完全了解了 fail-fast 是如何产生的!
即,当多个线程对同一个集合进行操作的时候,某线程访问集合的过程中,该集合的内容被其他线程所改变 (即其它线程通过 add、remove、clear 等方法,改变了 modCount 的值);这时,就会抛出 ConcurrentModificationException 异常,产生 fail-fast 事件。

5 解决 fail-fast 的原理

上面,说明了 “解决 fail-fast 机制的办法”,也知道了 “fail-fast 产生的根本原因”。接下来,我们再进一步谈谈 java.util.concurrent 包中是如何解决 fail-fast 事件的。
还是以和 ArrayList 对应的 CopyOnWriteArrayList 进行说明。我们先看看 CopyOnWriteArrayList 的源码:

img

img

[img](javascript:void(0)😉

1 package java.util.concurrent;
 2 import java.util.*;
 3 import java.util.concurrent.locks.*;
 4 import sun.misc.Unsafe;
 6 public class CopyOnWriteArrayList<E>
 7     implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
 9     ...
11     // 返回集合对应的迭代器
12     public Iterator<E> iterator() {
13         return new COWIterator<E>(getArray(), 0);
14     }
16     ...
18     private static class COWIterator<E> implements ListIterator<E> {
19         private final Object[] snapshot;
21         private int cursor;
23         private COWIterator(Object[] elements, int initialCursor) {
24             cursor = initialCursor;
25             // 新建COWIterator时,将集合中的元素保存到一个新的拷贝数组中。
26             // 这样,当原始集合的数据改变,拷贝数据中的值也不会变化。
27             snapshot = elements;
28         }
30         public boolean hasNext() {
31             return cursor < snapshot.length;
32         }
34         public boolean hasPrevious() {
35             return cursor > 0;
36         }
38         public E next() {
39             if (! hasNext())
40                 throw new NoSuchElementException();
41             return (E) snapshot[cursor++];
42         }
44         public E previous() {
45             if (! hasPrevious())
46                 throw new NoSuchElementException();
47             return (E) snapshot[--cursor];
48         }
50         public int nextIndex() {
51             return cursor;
52         }
54         public int previousIndex() {
55             return cursor-1;
56         }
58         public void remove() {
59             throw new UnsupportedOperationException();
60         }
62         public void set(E e) {
63             throw new UnsupportedOperationException();
64         }
66         public void add(E e) {
67             throw new UnsupportedOperationException();
68         }
69     }
71     ...
73 }

[img](javascript:void(0)😉

View Code

从中,我们可以看出:

(01) 和 ArrayList 继承于 AbstractList 不同,CopyOnWriteArrayList 没有继承于 AbstractList,它仅仅只是实现了 List 接口。
(02) ArrayList 的 iterator() 函数返回的 Iterator 是在 AbstractList 中实现的;而 CopyOnWriteArrayList 是自己实现 Iterator。
(03) ArrayList 的 Iterator 实现类中调用 next()时,会 “调用 checkForComodification() 比较‘expectedModCount’和‘modCount’的大小”;但是,CopyOnWriteArrayList 的 Iterator 实现类中,没有所谓的 checkForComodification(),更不会抛出 ConcurrentModificationException 异常!

那进一步的问题是,为什么CopyOnWriteArrayList 可以不使用checkForComodification()呢?

首先,CopyOnWriteArrayList 的迭代器在创建时是将数组中的元素复制了一遍的:

COWIterator(Object[] es, int initialCursor) {
            this.cursor = initialCursor;
            this.snapshot = es;
        }

然后,CopyOnWriteArrayList 的add等操作也是copy一份现有数据,在现有数据上修改好,在把原有数据的引用改成指向修改后的数据。还加上了同步锁以避免多线程同时add

public boolean addAll(int index, Collection<? extends E> c) {
            synchronized(CopyOnWriteArrayList.this.lock) {
                this.rangeCheckForAdd(index);
                Object[] oldArray = this.getArrayChecked();
                boolean modified = CopyOnWriteArrayList.this.addAll(this.offset + index, c);
                this.size += (this.expectedArray = CopyOnWriteArrayList.this.getArray()).length - oldArray.length;
                return modified;
            }
        }

相当于读写都是copy之后对副本进行的,而不直接对源数组进行。此外,数组还被声明为了volatile类型,这会要求,当线程 2 进行修改时,会导致线程 1 的工作内存中的缓存变量的缓存行无效(反映到硬件层的话,就是 CPU 的 L1 或者 L2 缓存中对应的缓存行无效):

private transient volatile Object[] array;

这样做的话,对数组的修改就能在完成后同步到各个线程中,但是并不会直接影响线程中正在进行的利用迭代器的读(不会同时写的,有同步锁),因为读的是副本,不会过期,所以可以正常地继续从工作空间中间读自己拷贝的副本,虽然工作空间中的CopyOnWriteArrayList 变量已经过期了。但是此时读的就不是最新的内容了,所以说CopyOnWriteArrayList保证的是弱一致性

posted @ 2020-03-10 10:37  别再闹了  阅读(118)  评论(0)    收藏  举报