jdk1.8源碼學習之HashMap

部分內容待完善... 


分析ConcurrentHashMap之前,首先要對Map和HashMap逐個分析,才能更好得理解ConcurrentHashMap。所以這片文章主要來分析HashMap。

1、Map簡介

如圖Map是一個接口,除此之外常用的集合類接口還有Collection

2、HashMap分析

2.1 源碼分析

jdk1.7與1.8關於hashmap做了些許改動,主要就是hash衝突時對數據的處理由1.7中的拉鍊法變爲了1.8中的紅黑樹(衝突數據大於8)。因爲1.8中的源碼過於複雜,所以這裏只分析幾個關鍵的方法和參數。

 

初始化容量

/** * The default initial capacity - MUST be a power of two. */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

首先來查看HashMap關於初始化容量的定義,這裏容量定義爲1<<4,也就是0001(二進制)左移4位變爲1000(二進制),也就是16。具體爲何這樣定義可以參考代碼註釋,主要是爲了提醒初始化容量需定義爲2的冪。

負載因子定義

/** * The load factor used when none specified in constructor. */
static final float DEFAULT_LOAD_FACTOR = 0.75f;

這裏負載因子定義爲0.75,即當前hashmap中實際大小大於16*0.75=12時,就要進行擴容

紅黑樹轉化閾值

/** * The bin count threshold for using a tree rather than list for a * bin.  Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */
static final int TREEIFY_THRESHOLD = 8;

上面註釋的大概意思是,拉鍊法中的節點大於8時,將會轉換爲紅黑樹。這樣就將時間複雜度O(n)變爲了O(lgn)


構造函數

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
}

 源碼中有好幾個重載的構造函數,但主要的還是這個方法。即傳入初始化大小和負載因子的方法。這個threshold的主要作用就是用來計算負載的。比如初始化長度爲12,那麼要在什麼情況下擴容呢?就是要找出最接近的2的冪,然後計算。比如找出16,在乘以負載因子0.75

大家可能會注意,最後一行有個tableSizeFor方法,傳入了一個初始化長度,下面就詳細說下這個方法。這個方法設計非常巧妙,主要就是返回大於當前長度最接近的2的n次冪,比如cap=12,則返回16,主要就是運用了位操作。

static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

我舉個長度爲12的例子

cap的二進制    0000 1100  //十進制爲12

n=cap-1即11    0000  1011 //十進制爲11  

n |= n >>> 1,這個操作是n與n右移一位然後進行或操作

0000 1011
0000 0101 
或操作後
0000 1111 此時的n
同理 n |= n >>> 2,這個操作是n與n右移兩位然後進行或操作
0000 1111
0000 0011
或操作後
0000 1111
....
最後發現n就是 0000 1111 即十進制的15

 經過上邊一串位操作後,會發現n結果等於15,然後返回n+1即16。可以發現,上邊的一串位操作其實就是把當前位即後邊的位都變爲1,這樣結果就爲2的n次冪減1了。

數據插入

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) //如果table爲0或空,則進行resize
            n = (tab = resize()).length;
        //這個是計算下標,取模操作,如果爲空,則直接插入
        if ((p = tab[i = (n - 1) & hash]) == null) 
            tab[i] = newNode(hash, key, value, null);
        //else的情況有兩種
        //1、key值一樣,則替換value
        //2、key不一樣,則拉鍊法,長度過長後轉換爲紅黑樹
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//此時e已經被賦值爲衝突的節點
            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
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
}

這裏基本上都做了註釋,具體可以看註釋。

Node節點定義

/** 
* Basic hash bin node, used for most entries.  (See below for 
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.) 
*/
static class Node<K,V> implements Map.Entry<K,V> {    
    final int hash;    
    final K key;    
    V value;    
    Node<K,V> next;    
    Node(int hash, K key, V value, Node<K,V> next) {        
        this.hash = hash;        
        this.key = key;        
        this.value = value;        
        this.next = next;    
    }    
    public final K getKey()        { return key; }   
    public final V getValue()      { return value; }    
    public final String toString() { return key + "=" + value; }    
    public final int hashCode() {        return Objects.hashCode(key) ^ Objects.hashCode(value);    }   
    public final V setValue(V newValue) {        
        V oldValue = value;        
        value = newValue;        
        return oldValue;    
    }    
    public final boolean equals(Object o) {        
        if (o == this)            
            return true;        
        if (o instanceof Map.Entry) {            
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;            
            if (Objects.equals(key, e.getKey()) &&                
                Objects.equals(value, e.getValue()))                
                return true;        
        }       
        return false;    
    }
}

這是HashMap中節點的定義,它其實是單項鍊表。

擴容算法實現

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//當前table容量
        int oldThr = threshold; //threshold爲當前hashmap負載情況,具體在tableSizeFor函數實現,默認爲16*0.75
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //把oldCap(舊錶長度左移兩位,即擴大兩倍)oldCap*2
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // 同樣閾值也要乘2
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            //把oldTab中的節點重新rehash到新的tab中去
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)//單節點的情況直接進行與操作定位
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)//對紅黑樹進行rehash
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // 對鏈表進行rehash
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

該段代碼主要是用來初始化hashmap或是對hashmap擴容,具體請看代碼註釋

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章