java - HashTable有没有采用快速失败机制?
问题描述
1,http://www.yq1012.com/api/jav...由所有类的“collection 视图方法”返回的 collection 的 iterator 方法返回的迭代器都是快速失败 的:在创建 Iterator 之后,如果从结构上对 Hashtable 进行修改,除非通过 Iterator 自身的 remove 方法,否则在任何时间以任何方式对其进行修改,Iterator 都将抛出ConcurrentModificationException。因此,面对并发的修改,Iterator 很快就会完全失败,而不冒在将来某个不确定的时间发生任意不确定行为的风险。由 Hashtable 的键和元素方法返回的 Enumeration 不 是快速失败的。
有地方说因为HashTable做了线程同步,所以没有采用快速失败机制
2,但是源码中hashtable.keySet.iterator 返回的iterator中有 做判断比如说iterator的remove方法 (在类: private class Enumerator<T> implements Enumeration<T>, Iterator<T>中)
public void remove() { if (!iterator)throw new UnsupportedOperationException(); if (lastReturned == null)throw new IllegalStateException('Hashtable Enumerator'); if (modCount != expectedModCount)throw new ConcurrentModificationException(); synchronized(Hashtable.this) {Entry[] tab = Hashtable.this.table;int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e == lastReturned) {modCount++;expectedModCount++;if (prev == null) tab[index] = e.next;else prev.next = e.next;count--;lastReturned = null;return; }}throw new ConcurrentModificationException(); }} public T next() { if (modCount != expectedModCount)throw new ConcurrentModificationException(); return nextElement();}
上面两端代码中都有验证 if (modCount != expectedModCount)
throw new ConcurrentModificationException();所以多线程环境下并发修改hashtable 也是会引起Iterator迭代失败,我代码测试过
这个该怎么理解,请问上面提到的哪种情况是正确的
问题解答
回答1:Hashtable的iterator遍历方式支持fast-fail,用Enumeration不支持fast-fail
相关文章:
1. docker - 各位电脑上有多少个容器啊?容器一多,自己都搞混了,咋办呢?2. javascript - JS用ajax爬取百度外卖店家信息3. dockerfile - 为什么docker容器启动不了?4. dockerfile - 我用docker build的时候出现下边问题 麻烦帮我看一下5. java - 为什么第一个线程已经释放了锁,第二个线程却不行?6. 在应用配置文件 app.php 中找不到’route_check_cache’配置项7. angular.js使用$resource服务把数据存入mongodb的问题。8. javascript - 编程,算法的问题9. 我在centos容器里安装docker,也就是在容器里安装容器,报错了?10. docker - 如何修改运行中容器的配置

网公网安备