关于java:JDK18-ConcurrentHashMap解析

1次阅读

共计 4984 个字符,预计需要花费 13 分钟才能阅读完成。

数据结构

JDK1.8ConcurrentHashMap 采纳数组 + 单链表 + 红黑树的数据结构,数组和链表存储的是一个个 Node 对象,红黑树存储的是 TreeNode 对象

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        volatile V val;
        volatile Node<K,V> next;
    }

    static final class TreeNode<K,V> extends Node<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,
                 TreeNode<K,V> parent) {super(hash, key, val, next);
            this.parent = parent;
        }
    } 
        

罕用办法

应用

源码剖析

次要属性

// 最大容量
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认容量
static final int DEFAULT_INITIAL_CAPACITY = 16;
// 数组最大容量
static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
// 加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表的树化阈值,即链表转成红黑树的阈值,当 Node 链表长度 > 该值时,则将链表转换成红黑树
static final int TREEIFY_THRESHOLD = 8; 
// 链表的还原阈值,即红黑树转为链表的阈值,当在扩容时,HashMap 的数据存储地位会从新计算,在从新计算存储地位后,当红黑树内 TreeNode 数量 < 6 时,则将 红黑树转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
// 最小链表树化容量阈值,即 当 Node 数组长度 > 该值时,才容许树形化链表,否则则间接扩容,而不是树形化
static final int MIN_TREEIFY_CAPACITY = 64;

构造方法

    public ConcurrentHashMap() {}

    public ConcurrentHashMap(int initialCapacity) {if (initialCapacity < 0)
            throw new IllegalArgumentException();
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        this.sizeCtl = cap;
    }


    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        this.sizeCtl = DEFAULT_CAPACITY;
        putAll(m);
    }

    public ConcurrentHashMap(int initialCapacity, float loadFactor) {this(initialCapacity, loadFactor, 1);
    }

    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
            throw new IllegalArgumentException();
        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        this.sizeCtl = cap;
    }

put()办法

    public V put(K key, V value) {return putVal(key, value, false);
    }

    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;
            //1.Node 数组初始化
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //2. 计算 key 寄存 Node 数组中的数组下标,判断这个数组下标 Node 数组上是否有 Node 存在    
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                //2.1 若不存在,阐明没有 hash 抵触,则示意以后地位能够写入数据,利用 CAS 尝试写入,失败则自旋保障胜利
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            //3. 以后地位的 hashcode==MOVED==-1,则进行扩容
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                //4. 存在 hash 抵触,利用 synchronized 锁锁住链表或者红黑树的头结点写入数据
                V oldVal = null;
                synchronized (f) {if (tabAt(tab, i) == f) {
                        //4.1 以后是 Node 是链表
                        if (fh >= 0) {
                            binCount = 1;
                            // 遍历以该 Node 为头结点的链表, 判断该 key 是否已存在
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                //// 若该 key 已存在,则用新 value 替换旧 value
                                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;
                                // 若该 key 不存在,则将 key-value 增加到 Node 数组中, 这里采纳尾插法
                                if ((e = e.next) == null) {
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        //4.1 以后是 Node 是红黑树
                        else if (f instanceof TreeBin) {
                            Node<K,V> p;
                            binCount = 2;
                            //// 向红黑树插入或更新数据(键值对),遍历红黑树判断该节点的 key 是否与传入 key 雷同,雷同则新 value 笼罩旧 value,不雷同则插入
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                //6. 如果链表中的 Node 节点 >8 则须要转换为红黑树
                if (binCount != 0) {if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        addCount(1L, binCount);
        return null;
    }
     

sizeCtl 值含意:
-1: 示意正在初始化
-n: 示意正在扩容
0: 示意还未初始化,默认值
大于 0:示意下一次扩容的阈值

initTable()办法


    private final Node<K,V>[] initTable() {Node<K,V>[] tab; int sc;
        while ((tab = table) == null || tab.length == 0) {        
            // 若以后有其余线程正在初始化,则让出 CPU 执行权,而后自旋
            if ((sc = sizeCtl) < 0)
                Thread.yield(); // lost initialization race; just spin
            // 若以后有没有其余线程正在初始化,将 sizeCtl 置为 -1,相当于拿到了锁
            else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
                try {if ((tab = table) == null || tab.length == 0) {int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                        // 初始化数组大小为 16
                        @SuppressWarnings("unchecked")
                        Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                        table = tab = nt;
                        // 下一次扩容的大小,0.75n, 和以前的扩容阀值绝对应
                        sc = n - (n >>> 2);
                    }
                } finally {sizeCtl = sc;}
                break;
            }
        }
        return tab;
    }  

get()办法

    public V get(Object key) {Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        // 计算 key 寄存 Node 数组中的数组下标,判断这个数组下标 Node 数组上是否有 Node 存在
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            1. 在 Node 数组中找 key 相等的 Node
            if ((eh = e.hash) == h) {if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            //2. 在红黑树中找 key 相等的 Node 
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            //3. 在链表中找 key 相等的 Node 
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }

论断

1.JDK1.8ConcurrentHashMap 采纳数组 + 单链表 + 红黑树的数据结构,数组和链表存储的是一个个 Node 对象,红黑树存储的是 TreeNode 对象
2. 采纳了 CAS + synchronized 来保障并发安全性
3. 增加 key-value 时会依据 key 值计算出对应的 hash 值,依据 hash 值计算出对应的 Node 数组下标,判断这个数组下标 Node 数组上是否有 Node 存在,若不存在,阐明没有 hash 抵触,则示意以后地位能够写入数据,利用 CAS 尝试写入,失败则自旋保障胜利;若存在阐明有 hash 抵触,利用 synchronized 锁锁住链表或者红黑树的头结点写入数据

ConcurrentHashMap1.8 与 ConcurrentHashMap1.7 的区别:
1.1.7 采纳数组 + 链表,1.8 采纳数据 + 链表 + 红黑树优化了查问速度
2.1.7 采纳 Segment 分段锁,1.8 采纳 CAS + synchronized 升高锁的粒度:JDK1.7 版本锁的粒度是基于 Segment 的,蕴含多个 HashEntry,而 JDK1.8 锁的粒度就是 HashEntry

正文完
 0