我是靠谱客的博主 笑点低毛豆,这篇文章主要介绍Java Collection的Fail fast与Fail safe迭代器,现在分享给大家,希望可以做个参考。

Java Collection框架提供了迭代器Iterator用于遍历集合元素,有以下两种迭代器

Fail fast Iterator

大多数 Java 1.4 的Collection类,如Vector,ArrayList,HashSet,以及HashMap,提供的都是Fail fast行为的迭代器。指的是当迭代器正在遍历Collection时,若当前线程或其他线程对Collection元素进行添加,删除或更新操作,就会抛出ConcurrentModificationException异常

具体实现是通过计数器来跟踪元素的添加,删除,更新等操作,以HashMap为例

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { ... // modCount计数器,对集合元素的操作都会增加modCount的值 transient int modCount; ... } private abstract class HashIterator<E> implements Iterator<E> { HashIterator() { // 记录遍历开始时的modCount expectedModCount = modCount; ... } final Entry<K,V> nextEntry() { // 若modCount改变,就抛出ConcurrentModificationException if (modCount != expectedModCount) throw new ConcurrentModificationException(); ... } }

以下HashMap的例子将抛出ConcurrentModificationException异常

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class FailFastIterators { public static void main(String[] args) { Map<String, Integer> marks = new HashMap<String, Integer>(); marks.put("Maths", new Integer(129)); marks.put("Science", new Integer(139)); marks.put("Sanskrit", new Integer(94)); Iterator iter = marks.keySet().iterator(); while(iter.hasNext()) { System.out.println(marks.get(iter.next())); marks.remove("Science"); } } }
复制代码
1
2
3
4
5
6
7
控制台输出: 129 Exception in thread “main” java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(Unknown Source) at java.util.HashMap$KeyIterator.next(Unknown Source) at tutorials.FailFastIterators.main(FailFastIterators.java:30)

需要注意的是,modCount的操作并不是synchronized,因此并不保证当元素有变动时,一定会抛出异常,开发人员也不应该依赖此异常来判断元素的变动

Fail safe Iterator

Fail safe迭代器则不会抛出上述异常,因为其工作在Collection的一个备份上,而不是Collection本身;CopyOnArrayListConcurrentHashMap的迭代器就是Fail safe行为的

我们将上一个例子换成ConcurrentHashMap

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class FailFastIterators { public static void main(String[] args) { Map<String, Integer> marks = new ConcurrentHashMap<String, Integer>(); marks.put("Maths", new Integer(129)); marks.put("Science", new Integer(139)); marks.put("Sanskrit", new Integer(94)); Iterator iter = marks.keySet().iterator(); while(iter.hasNext()) { System.out.println(marks.get(iter.next())); marks.remove("Science"); } } }
复制代码
1
2
3
4
控制台输出: 129 94

最后

以上就是笑点低毛豆最近收集整理的关于Java Collection的Fail fast与Fail safe迭代器的全部内容,更多相关Java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部