HashMap之快速失败

HashMap之快速失败

为什么HashMap通过迭代器自身的remove或add方法就不会出现迭代器失败?

HashMap所有集合类视图所返回迭代器都是快速失败(fast-fail)的

在HashMap中,有一个变量modCount来指示集合被修改的次数。在创建Iterator迭代器的时候,会给这个变量赋值给expectedModCount。当集合方法修改集合元素时,例如集合的remove()方法时,此时会修改modCount值,但不会同步修改expectedModCount值。当使用迭代器遍历元素操作时,会首先对比expectedModCount与modCount是否相等。如果不相等,则马上抛出java.util.ConcurrentModificationException异常。而通过Iterator的remove()方法移除元素时,会同时更新expectedModCount的值,将modCount的值重新赋值给expectedModCount,这样下一次遍历时,就不会发抛出ava.util.ConcurrentModificationException异常。

具体从代码来看。

首先看HashMap的remove方法:

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

/**
 * Implements Map.remove and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to match if matchValue, else ignored
 * @param matchValue if true only remove if value is equal
 * @param movable if false do not move other nodes while removing
 * @return the node, or null if none
 */
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            //在真正移除节点时,修改modCount的值
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

 /**
 * The number of times this HashMap has been structurally modified
 * Structural modifications are those that change the number of mappings in
 * the HashMap or otherwise modify its internal structure (e.g.,
 * rehash).  This field is used to make iterators on Collection-views of
 * the HashMap fail-fast.  (See ConcurrentModificationException).
 */
transient int modCount;//指示HashMap被修改的次数

当通过remove移除HashMap中的一个元素时,会修改modCount值,其他修改HashMap集合的方法也会修改modCount值。该值在创建迭代器的时候,会赋值给expectedModCount,在迭代器工作的时候,会判定检查modCount值是否修改了。如果该值被修改了,则抛出ConcurrentModificationException异常。HashMap的Value迭代器实现如下:

final class ValueIterator extends HashIterator
    implements Iterator<V> {
    public final V next() { return nextNode().value; }
}

abstract class HashIterator {
    Node<K,V> next;        // next entry to return
    Node<K,V> current;     // current entry
    int expectedModCount;  // for fast-fail
    int index;             // current slot

    HashIterator() {
        //在构造迭代器的时候,将modCount值赋值给expectedModCount
        expectedModCount = modCount;
        Node<K,V>[] t = table;
        current = next = null;
        index = 0;
        if (t != null && size > 0) { // advance to first entry
            do {} while (index < t.length && (next = t[index++]) == null);
        }
    }

    public final boolean hasNext() {
        return next != null;
    }

    final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;
        //在获取下一个节点前,先判定modCount值是否修改,如果被修改了则抛出ConcurrentModificationException异常,从前面可以知道,当修改了HashMap的时候,都会修改modCount值。
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        if ((next = (current = e).next) == null && (t = table) != null) {
            do {} while (index < t.length && (next = t[index++]) == null);
        }
        return e;
    }

    //迭代器的删除操作,会重新给exceptedModCount赋值,因此不会导致fast-fail
    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        //先判定modCount值是否被修改了
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        //将modCount值重新赋值给expectedModCount,这样下次迭代时,不会出现fast-fail
        expectedModCount = modCount;
    }
}

可以看到,通过迭代器remove一个元素,虽然会改变modCount值,但会将modCount值重新赋值为expectedModCount,这样下次再迭代时,不会出现fast-fail。而通过HashMap的remove方法会修改modCount值,但不会更新迭代器的expectedModCount值,所以迭代器在迭代操作时,会抛出ConcurrentModificationException异常。

如果从结构上对映射进行修改,除非通过迭代器自身的 remove 或 add 方法,其他任何时间任何方式的修改,迭代器都将抛出 ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败。注意,迭代器的快速失败行为不能得到保证,一般来说,存在不同步的并发修改时,不能作出任何坚决的保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。

具体的例子可以参考文章:关于List比较好玩的操作

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HashMap和ConcurrentHashMap都是Java中的Map实现,它们之间的区别如下: 1. 线程安全性 HashMap是非线程安全的,而ConcurrentHashMap是线程安全的。HashMap在多线程环境下,如果有多个线程同时对同一个HashMap进行修改操作,可能会导致数据不一致或者死锁等问题。而ConcurrentHashMap使用了一种分段锁(Segment)的机制来实现线程安全,可以支持多个线程同时对不同的数据段进行修改操作。 2. 性能 在单线程环境下,HashMap的性能比ConcurrentHashMap要好。但在多线程环境下,ConcurrentHashMap的性能要优于HashMap,尤其是在读多写少的情况下。 3. 迭代器 ConcurrentHashMap的迭代器是弱一致性的,而HashMap的迭代器是快速失败的。弱一致性的迭代器是指在迭代过程中允许多线程对数据进行修改,但不能保证迭代器能够准确地反映出所有修改后的结果。而快速失败的迭代器则是指在迭代过程中,如果发现其他线程修改了数据,会立即抛出ConcurrentModificationException异常。 4. 数据一致性 ConcurrentHashMap不保证数据的强一致性,只保证数据的最终一致性。最终一致性是指,在多线程环境下,如果没有新的修改操作,那么所有线程对数据的访问结果是一样的。而强一致性则是指,在多线程环境下,无论是否有新的修改操作,所有线程对数据的访问结果都是一样的。 总的来说,ConcurrentHashMap是线程安全的,适用于高并发场景下的多线程操作;而HashMap是非线程安全的,适用于单线程环境下的操作。但是需要注意的是,在并发环境下,ConcurrentHashMap的数据一致性可能会受到影响,需要根据具体情况选择使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值