素材牛VIP会员
HashTable有没有采用快速失败机制?
 su***se  分类:Java代码  人气:656  回帖:1  发布于6年前 收藏

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迭代失败,我代码测试过
            
            
            

这个该怎么理解,请问上面提到的哪种情况是正确的

 标签:java

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv6 码匠
这***生 技术总监 6年前#1

Hashtable的iterator遍历方式支持fast-fail,用Enumeration不支持fast-fail

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取