4.源碼中的HashMap與JUC之ConcurrentHashMap

1.HashMap源碼分析

首先了解一下jdk1.8 HashMap的存儲原理:鏈表+數組+紅黑樹,並且可自動擴容。

一張圖加源碼搞定HashMap源碼

原理分析圖:
在這裏插入圖片描述

//hashmap源碼
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // 哈希表的負載因子,默認爲0.75,可自己指定
    }
//hashmap默認容量 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

put方法中關鍵信息:

  final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i; //tab爲數組,p爲數據節點
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length; //數組長度
        if ((p = tab[i = (n - 1) & hash]) == null) //當數組中hash值不重複時,直接以數組形式存在
            tab[i] = newNode(hash, key, value, null); //創建一個新節點放入數組中,節點node信息: hash、key、value、next:指向下一個節點得地址:node-->next node
        else { //當數組中hash值重複時,將數據以鏈表形式存儲
            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); //上一個Node的next指向下一個節點
                        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) //threshold:計算擴容的閾值
            resize();//resize(根據負載因子*默認容量=計算擴容的閾值 判斷容量是否不足,嘗試去自動擴容)
        afterNodeInsertion(evict);
        return null;
    }

2.ConcurrentHashMap源碼分析

個人看來: 只是再put操作時加入的鎖和cas控制保證線程安全,基本數據結構不變。

 final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());
        int binCount = 0;
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                if (casTabAt(tab, i, null, //cas compareAndset 利用java內部的原子性操作保證線程安全
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                synchronized (f) { //利用synchronized 鎖機制保證線程安全
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            binCount = 1;
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        else if (f instanceof TreeBin) {
                            Node<K,V> p;
                            binCount = 2;
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }

注意:以上代碼都來自jdk源碼。
上一篇:3.線程池的使用
[下一篇:敬請期待]

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