Hashmap在JDK8中的提升,HashmapJDK8提升
HashMap使用key的hashCode()和equals()方法來將值劃分到不同的桶裡。桶的數量通常要比map中的記錄的數量要稍大,這樣 每個桶包括的值會比較少(最好是一個)。當通過key進行尋找時,我們可以在常數時間內迅速定位到某個桶(使用hashCode()對桶的數量進行模數) 以及要找的對象。
這些東西你應該都已經知道了。你可能還知道雜湊碰撞會對hashMap的效能帶來災難性的影響。如果多個hashCode()的值落到同一個桶內的 時候,這些值是儲存到一個鏈表中的。最壞的情況下,所有的key都映射到同一個桶中,這樣hashmap就退化成了一個鏈表——尋找時間從O(1)到 O(n)。
當然這是在jdk8以前,JDK1.6中HashMap採用的是位桶+鏈表的方式,即我們常說的散列鏈表的方式,而JDK1.8中採用的是位桶+鏈表/紅/黑樹狀結構的方式,也是非安全執行緒的。當某個位桶的鏈表的長度達到某個閥值的時候,這個鏈表就將轉換成紅/黑樹狀結構。
看下面的代碼
//鏈表節點static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; //省略 }//紅/黑樹狀結構節點static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } //省略 }// HashMap的主要屬性public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { // 槽數組,Node<K,V>類型,TreeNode extends LinkedHashMap.Entry<K,V>,所以可以存放TreeNode來實現Tree bins transient Node<K,V>[] table; transient Set<Map.Entry<K,V>> entrySet; transient int size; // 去掉了volatile的修飾符 transient int modCount; int threshold; final float loadFactor; ...}
//計算key的hashstatic final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }飯後我們在看看具體的put和get方法
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; //hash & length-1 定位元組下標 if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { /*第一個節點是TreeNode,則採用位桶+紅/黑樹狀結構結構, * 調用TreeNode.getTreeNode(hash,key), *遍曆紅/黑樹狀結構,得到節點的value */ if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } final TreeNode<K,V> getTreeNode(int h, Object k) { //找到紅/黑樹狀結構的根節點並遍曆紅/黑樹狀結構 return ((parent != null) ? root() : this).find(h, k, null); } /* *通過hash值的比較,遞迴的去遍曆紅/黑樹狀結構,這裡要提的是compareableClassFor(Class k)這個函數的作用,在某些時候 *如果紅/黑樹狀結構節點的元素are of the same "class C implements Comparable<C>" type *利用他們的compareTo()方法來比較大小,這裡需要通過反射機制來check他們到底是不是屬於同一個類,是不是具有可比較性. */ final TreeNode<K,V> find(int h, Object k, Class<?> kc) { TreeNode<K,V> p = this; do { int ph, dir; K pk; TreeNode<K,V> pl = p.left, pr = p.right, q; if ((ph = p.hash) > h) p = pl; else if (ph < h) p = pr; else if ((pk = p.key) == k || (k != null && k.equals(pk))) return p; else if (pl == null) p = pr; else if (pr == null) p = pl; else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0) p = (dir < 0) ? pl : pr; else if ((q = pr.find(h, k, kc)) != null) return q; else p = pl; } while (p != null); return null; }
//put(K key,V value)函數 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; //如果table為空白或者長度為0,則resize() if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //找到key值對應的槽並且是第一個,直接加入 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //第一個node的hash值即為要加入元素的hash if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))){ e = p; }else if (p instanceof TreeNode)//第一個節點是TreeNode,即tree-bin /*Tree version of putVal. *final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,int h, K k, V v) */ e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { //不是TreeNode,即為鏈表,遍曆鏈表 for (int binCount = 0; ; ++binCount) { /*到達鏈表的尾端也沒有找到key值相同的節點, *則產生一個新的Node,並且判斷鏈表的節點個數是不是到達轉換成紅/黑樹狀結構的上界 *達到,則轉換成紅/黑樹狀結構 */ 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 V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); //返回舊的value值 return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null;}
HashMap會動態使用一個專門的treemap實現來替換掉它。這樣做的結果會更好,是O(logn),而不是糟糕的O(n)。它是如何工作 的?前面產生衝突的那些KEY對應的記錄只是簡單的追加到一個鏈表後面,這些記錄只能通過遍曆來進行尋找。但是超過這個閾值後HashMap開始將列表升 級成一個二叉樹,使用雜湊值作為樹的分支變數,如果兩個雜湊值不等,但指向同一個桶的話,較大的那個會插入到右子樹裡
個效能提升有什麼用處?比方說惡意的程式,如果它知道我們用的是雜湊演算法,它可能會發送大量的請求,導致產生嚴重的雜湊碰撞。然後不停的訪問這些 key就能顯著的影響伺服器的效能,這樣就形成了一次拒絕服務的攻擊(DoS)。JDK 8中從O(n)到O(logn)的飛躍,可以有效地防止類似的攻擊,同時也讓HashMap效能的可預測性稍微增強了一些。
轉載請註明出處http://blog.csdn.net/a837199685