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使用弱一致性迭代器,遍歷時,能夠修改,增長了不肯定性,這須要我使用時注意。對象