ArrayList的Fail-Fast机制?

fail-fast简介

fail-fast是集合中比较常见的错误检测机制。一般在对集合元素进行遍历的时候发生。打个不恰当的比喻,正在清点仓库的每样物品,突然被加塞进来或者被拿走了一些,为了保证清点结果准确,当作清点有误,要重新开始。对于ArrayList来说,首先它是线程不安全的,快速失败机制也常见于多线程的情况,单线程也会发生。ArrayList的快速失败发生的前提是必须是用了迭代器进行遍历。下面用几种情况说明发生的原理。
fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。
例如:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出
ConcurrentModificationException异常,产生fail-fast事件。

fail-fast解决办法

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

fail-fast原理

ConcurrentModificationException是在操作Iterator时抛出的异常。我们先看看Iterator的源码。ArrayList的Iterator是在父类AbstractList.java中实现的。代码如下:
1 package java.util;
2
3 public abstract class AbstractList extends AbstractCollection implements List {
4
5 …
6
7 // AbstractList中唯一的属性
8 // 用来记录List修改的次数:每修改一次(添加/删除等操作),将modCount+1
9 protected transient int modCount = 0;
10
11 // 返回List对应迭代器。实际上,是返回Itr对象。
12 public Iterator iterator() {
13 return new Itr();
14 }
15
16 // Itr是Iterator(迭代器)的实现类
17 private class Itr implements Iterator {
18 int cursor = 0;
19
20 int lastRet = -1;
21
22 // 修改数的记录值。
23 // 每次新建Itr()对象时,都会保存新建该对象时对应的modCount;
24 // 以后每次遍历List中的元素的时候,都会比较expectedModCount和modCount是否相等;
25 // 若不相等,则抛出ConcurrentModificationException异常,产生fail-fast事件。
26 int expectedModCount = modCount;
27
28 public boolean hasNext() {
29 return cursor != size();
30 }
31
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 }
45
46 public void remove() {
47 if (lastRet == -1)
48 throw new IllegalStateException();
49 checkForComodification();
50
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 }
61
62 final void checkForComodification() {
63 if (modCount != expectedModCount)
64 throw new ConcurrentModificationException();
65 }
66 }
67
68 …
69 }
从中,我们可以发现在调用 next() 和 remove()时,都会执行 checkForComodification()。若 “modCount 不等于 expectedModCount”,则抛出
ConcurrentModificationException异常,产生fail-fast事件。

要搞明白 fail-fast机制,我们就要需要理解什么时候“modCount 不等于 expectedModCount”!
从Itr类中,我们知道 expectedModCount 在创建Itr对象时,被赋值为 modCount。通过Itr,我们知道:expectedModCount不可能被修改为不等于 modCount。所以,需要考证的就是modCount何时会被修改
接下来,我们查看ArrayList的源码,来看看modCount是如何被修改的。
1 package java.util;
2
3 public class ArrayList extends AbstractList
4 implements List, RandomAccess, Cloneable, java.io.Serializable
5 {
6
7 …
8
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 }
22
23
24 // 添加元素到队列最后
25 public boolean add(E e) {
26 // 修改modCount
27 ensureCapacity(size + 1); // Increments modCount!!
28 elementData[size++] = e;
29 return true;
30 }
31
32
33 // 添加元素到指定的位置
34 public void add(int index, E element) {
35 if (index > size || index < 0)
36 throw new IndexOutOfBoundsException(
37 "Index: “+index+”, Size: "+size);
38
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 }
46
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 }
57
58
59 // 删除指定位置的元素
60 public E remove(int index) {
61 RangeCheck(index);
62
63 // 修改modCount
64 modCount++;
65 E oldValue = (E) elementData[index];
66
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
71
72 return oldValue;
73 }
74
75
76 // 快速删除指定位置的元素
77 private void fastRemove(int index) {
78
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 }
87
88 // 清空集合
89 public void clear() {
90 // 修改modCount
91 modCount++;
92
93 // Let gc do its work
94 for (int i = 0; i < size; i++)
95 elementData[i] = null;
96
97 size = 0;
98 }
99
100 …
101 }
从中,我们发现:无论是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事件。

解决fail-fast的原理

上面,说明了“解决fail-fast机制的办法”,也知道了“fail-fast产生的根本原因”。接下来,我们再进一步谈谈java.util.concurrent包中是如何解决fail-fast事件的。
还是以和ArrayList对应的CopyOnWriteArrayList进行说明。我们先看看CopyOnWriteArrayList的源码:
1 package java.util.concurrent;
2 import java.util.;
3 import java.util.concurrent.locks.
;
4 import sun.misc.Unsafe;
5
6 public class CopyOnWriteArrayList
7 implements List, RandomAccess, Cloneable, java.io.Serializable {
8
9 …
10
11 // 返回集合对应的迭代器
12 public Iterator iterator() {
13 return new COWIterator(getArray(), 0);
14 }
15
16 …
17
18 private static class COWIterator implements ListIterator {
19 private final Object[] snapshot;
20
21 private int cursor;
22
23 private COWIterator(Object[] elements, int initialCursor) {
24 cursor = initialCursor;
25 // 新建COWIterator时,将集合中的元素保存到一个新的拷贝数组中。
26 // 这样,当原始集合的数据改变,拷贝数据中的值也不会变化。
27 snapshot = elements;
28 }
29
30 public boolean hasNext() {
31 return cursor < snapshot.length;
32 }
33
34 public boolean hasPrevious() {
35 return cursor > 0;
36 }
37
38 public E next() {
39 if (! hasNext())
40 throw new NoSuchElementException();
41 return (E) snapshot[cursor++];
42 }
43
44 public E previous() {
45 if (! hasPrevious())
46 throw new NoSuchElementException();
47 return (E) snapshot[–cursor];
48 }
49
50 public int nextIndex() {
51 return cursor;
52 }
53
54 public int previousIndex() {
55 return cursor-1;
56 }
57
58 public void remove() {
59 throw new UnsupportedOperationException();
60 }
61
62 public void set(E e) {
63 throw new UnsupportedOperationException();
64 }
65
66 public void add(E e) {
67 throw new UnsupportedOperationException();
68 }
69 }
70
71 …
72
73 }
从中,我们可以看出:

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

注释

  1. 单线程-普通for遍历 不会报异常
  2. 单线程-迭代器遍历 会报异常
  3. 单线程-增强for遍历 会报异常

fail-safe机制有两个问题

(1)需要复制集合,产生大量的无效对象,开销大

(2)无法保证读取的数据是目前原始数据结构中的数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~有思想的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值