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>()); } }
结果:java
HashMap会抛出java.util.ConcurrentModificationException异常;ConcurrentHashMap会正常执行。安全
为何HashMap会抛出异常?app
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已经存在呢?this
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,不会抛出异常。spa
但ConcurrentHashMap使用弱一致性迭代器,不检查修改次数。线程
为何两个Map选用不一样的迭代器?code
HashMap是线程不安全的,使用fail-fast? 但synchronizedMap是线程安全的,使用的也是fail-fast。我以为迭代过程当中,更多的是要遍历,而不是为了修改,fail-fast 是常态。 concurrentHashMap使用弱一致性迭代器,遍历时,能够修改,增长了不肯定性,这须要我使用时注意。对象