集合框架—两种迭代机制
迭代器fail-fast 机制是java集合(Collection)中的一种错误机制。
在我们详细讨论这两种机制的区别之前,首先得先了解并发修改。
2.什么是 fail-fast 机制?
迭代器在遍历过程中是直接访问内部数据的,因此内部的数据在遍历的过程中无法被修改。为了保证不被修改,迭代器内部维护了一个标记 "mode" ,当集合结构改变(添加删除或者修改),标记"mode"会被修改,而迭代器每次的hasNext()和next()方法都会检查该"mode"是否被改变,当检测到被修改时,抛出Concurrent Modification Exception
(迭代器的快速失败行为应该仅用于检测 bug。)
。下面看看ArrayList迭代器部分的源码
[java] view plain copy
1. private class Itr implements Iterator<E> {
2. int cursor;
3. int lastRet = -1;
4. int expectedModCount = ArrayList.this.modCount;
5.
6. public boolean hasNext() {
7. return (this.cursor != ArrayList.this.size);
8. }
9.
10. public E next() {
11. checkForComodification();
12. /** 省略此处代码 */
13. }
14.
15. public void remove() {
16. if (this.lastRet < 0)
17. throw new IllegalStateException();
18. checkForComodification();
19. /** 省略此处代码 */
20. }
21.
22. final void checkForComodification() {
23. if (ArrayList.this.modCount == this.expectedModCount)
24. return;
25. throw new ConcurrentModificationException();
26. }
27. }
可以看到它的标记"mode"为 expectedModeCount
4. fail-safe机制
fail-safe任何对集合结构的修改都会在一个复制的集合上进行修改,因此不会抛出ConcurrentModificationException
fail-safe机制有两个问题
(1)需要复制集合,产生大量的无效对象,开销大
(2)无法保证读取的数据是目前原始数据结构中的数据。
6. fail-fast和 fail-safe 的区别
Fail Fast Iterator | Fail Safe Iterator | |
Throw ConcurrentModification Exception | Yes | No |
Clone object | No | Yes |
Memory Overhead 存储开销 | No | Yes |
Examples | HashMap,Vector,ArrayList,HashSet | CopyOnWriteArrayList, ConcurrentHashMap 并发集合类 |
并发集合类以空间换时间的思想,和多线程局部变量ThreadLocation实现同步的思想一致