HashMap和ConcurrentHashMap的迭代器

public class _01_普通map的错误 {

    public static void useMap(final Map<String,Integer> scores) {
        scores.put("WU",19);
        scores.put("zhang",14);
        try {
            for(final String key : scores.keySet()) {
                System.out.println(key + ":" + scores.get(key));
                scores.put("liu",12);
            }
        }catch (Exception ex) {
            System.out.println("traverse key fail:" + ex);
        }

        try {
            for (final Integer value : scores.values()) {
                scores.put("liu", 13);
//                scores.put("zhao", 13); 
                System.out.println(value);
            }
        }catch (Exception ex){
            System.out.println("traverse value fail:" + ex);
        }
    }
    public static void main(String[] args) {
        System.out.println("Using Plain vanilla HashMap");
        useMap(new HashMap<String, Integer>());
        System.out.println("Using synchronized HashMap");    //不能在迭代遍历的同时,对map做更新
        useMap(Collections.synchronizedMap(new HashMap<String, Integer>()));

        System.out.println("Using concurrent HashMap"); //能够更新
        useMap(new ConcurrentHashMap<String, Integer>());
    }
}

结果:

HashMap会抛出java.util.ConcurrentModificationException异常;ConcurrentHashMap会正常执行。

为什么HashMap会抛出异常?

HashMap的 keySet(), values(), 都使用的强一致性迭代器,每一次获取节点元素,都要检查map的操作次数。

public Set<K> keySet() {
    Set<K> ks;
    // 1 调用HashMap的keySet()函数,会生成一个KeySet()对象
    return (ks = keySet) == null ? (keySet = new KeySet()) : ks;
}

final class KeySet extends AbstractSet<K> {
    public final int size()                 { return size; }
    public final void clear()               { HashMap.this.clear(); }
    //2 遍历时,生成KeySet的迭代器KeyIterator
    public final Iterator<K> iterator()     { return new KeyIterator(); }
    public final boolean contains(Object o) { return containsKey(o); }
    public final boolean remove(Object key) {
        return removeNode(hash(key), key, null, false, true) != null;
    }
    public final Spliterator<K> spliterator() {
        return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
    }
    public final void forEach(Consumer<? super K> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }
}


final class KeyIterator extends HashIterator
    implements Iterator<K> {
    //3. 遍历,获取下一个元素,nextNode()在HashIterator中实现。返回的是final类型,所以迭代器遍历返回值不能修改。
    public final K next() { return nextNode().key; }
}



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() {
     //4 modCount 是HashMap的成员变量,记录修改次数。增加、删除、清空元素都会加1. 把当前的修改次数赋值给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;
        //5 每一次返回元素,都会检查数量是否相同。如果不相同,则报异常。
        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;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        expectedModCount = modCount;
    }
}

由上,可知,在遍历过程中,引起modCount变化的会抛异常。但put(k,v), 如果k已经存在呢?

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
        // 1 如果key已经存在,会更新value,并返回旧的value,但不会更改modCount
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

因此,迭代器可以修改已经存在的key的value,不会抛出异常。

但ConcurrentHashMap使用弱一致性迭代器,不检查修改次数。

为什么两个Map选用不同的迭代器?

HashMap是线程不安全的,使用fail-fast? 但synchronizedMap是线程安全的,使用的也是fail-fast。我觉得迭代过程中,更多的是要遍历,而不是为了修改,fail-fast 是常态。 concurrentHashMap使用弱一致性迭代器,遍历时,可以修改,增加了不确定性,这需要我使用时注意。

转载于:https://my.oschina.net/u/1537182/blog/655814

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值