Hashmap在JDK8中的提升

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的hash
static 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

發佈了34 篇原創文章 · 獲贊 37 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章