ConcurrentHashMap 分析-源码

412 阅读15分钟

引言

本来没打算写 ConcurrentHashMap 的,偶然间和朋友聊天谈到了这里,就想应该写一下,毕竟和我上篇文章(synchronized)相比要简单多了。我看了很多面经,也都要求说一下 ConcurrentHashMap 了。所以,早晚都要学,那就趁这次机会详细记录一下吧。

正文

属性

private static final int MAXIMUM_CAPACITY = 1 << 30;
// 散列表默认值
private static final int DEFAULT_CAPACITY = 16;
// 加载因子
private static final float LOAD_FACTOR = 0.75f;
// 树化阈值,指定桶位链表长度达到 8 可能发生树化操作
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转化为链表的阈值
static final int UNTREEIFY_THRESHOLD = 6;
// 联合 TREEIFY_THRESHOLD 控制桶位是否树化,只有当 table 数组长度到达 64 且某个桶位
// 下的链表长度达到 8,才会发生树化
static final int MIN_TREEIFY_CAPACITY = 64;
// 线程迁移数据最小步长,控制线程迁移任务最小区间的一个值
private static final int MIN_TRANSFER_STRIDE = 16;
// 扩容相关,计算扩容时生成的一个 标识戳
private static int RESIZE_STAMP_BITS = 16;
// 并发扩容最多线程数
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;

// 当 node 节点的 hash 值为 -1 时,表示当前节点是 FWD 节点
static final int MOVED     = -1; 
// 当 node 节点的 hash 值为 -2 时,表示当前节点已树化,当前节点为 TreeBin 对象,
// treebin 对象代理操作红黑树
static final int TREEBIN   = -2; 
static final int RESERVED  = -3; // 用不到
// 可以将一个负数变成一个正数,但不是取绝对值
static final int HASH_BITS = 0x7fffffff; 
// 当前系统的 CPU 数量
static final int NCPU = Runtime.getRuntime().availableProcessors();
// 扩容过程中,会将扩容中的新 table 赋值给 nextTable 保持引用,扩容结束后,这里会被置为null
private transient volatile Node<K,V>[] nextTable;

有些没什么大用的属性没有写,无关紧要。但这些代码你会发现都是用 final 修饰的,也就是说 ConcurrentHashMap 没想让你改。

// 散列表,长度一定是 2 的次方树
transient volatile Node<K,V>[] table;
// LongAdder 中的 baseCount 未发生竞争时 或者 当前 LongAdder 处于加锁状态时,增量累加到 baseCount 中
private transient volatile long baseCount;
// LongAdder 中的 cellsBusy 0 表示当前 LongAdder 对象无锁状态,1 表示当前 LongAdder 对象加锁状态
private transient volatile int cellsBusy;
// LongAdder 中的 cells 数组,当 baseCount 发生竞争后,会创建 Cells 数组
// 线程会通过计算 hash 值取到自己的 cell,将增量累加到指定的 cell 中
// 总数 = sum(cells) + baseCount
private transient volatile CounterCell[] counterCells;
/**
 * sizeCtl < 0
 * 1. -1 表示当前table正在初始化(有线程在创建table数组),当前线程需要自旋等待..
 * 2.表示当前table数组正在进行扩容 ,高16位表示:扩容的标识戳   低16位表示:(1 + nThread) 当前参与并发扩容的线程数量
 *
 * sizeCtl = 0,表示创建table数组时 使用DEFAULT_CAPACITY为大小
 *
 * sizeCtl > 0
 *
 * 1. 如果table未初始化,表示初始化大小
 * 2. 如果table已经初始化,表示下次扩容时的 触发条件(阈值)
 */
private transient volatile int sizeCtl;
/**
 * 扩容过程中,记录当前进度。所有线程都需要从transferIndex中分配区间任务,去执行自己的任务。
 */
private transient volatile int transferIndex;

小方法

// 得到一个正数 hash 值
static final int spread(int h) {
    return (h ^ (h >>> 16)) & HASH_BITS;
}
// 获取 table 中指定下标的元素并返回
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
// 通过 CAS 的方式去数组中指定位置去设置值,设置成功返回 true
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
                                    Node<K,V> c, Node<K,V> v) {
    return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
// 返回 >= c 的最小的 2 的次方数
private static final int tableSizeFor(int c) {
        int n = c - 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;
    }

put 方法

计算每个线程可以处理的桶区间。默认 16. 初始化临时变量 nextTable,扩容 2 倍。 死循环,计算下标。完成区间,步长 判断。 如果桶内有数据,同步转移数据。通常会像链表拆成 2 份

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

/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
    if (key == null || value == null) throw new NullPointerException();
    int hash = spread(key.hashCode());
    //binCount表示当前k-v 封装成node后插入到指定桶位后,在桶位中的所属链表的下标位置
    //0 表示当前桶位为null,node可以直接放着
    //2 表示当前桶位已经可能是红黑树
    int binCount = 0;
    for (Node<K,V>[] tab = table;;) {
        // f 桶位的头结点
        // n 表示散列表的数组长度
        // i 表示 key 通过寻址计算后,得到的桶位下标
        // fh 表示桶位头节点的 hash 值
        Node<K,V> f; int n, i, fh;
        // 条件成立,表示当前 map 中的 table尚未初始化,延迟加载
        if (tab == null || (n = tab.length) == 0)
            tab = initTable();
        // i 表示 key 使用路由寻址算法得到 key 对应
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
            // 进入这里的前置条件是:table[i] == null
            // 使用 cas 的方式 设置 指定数组 i 桶为创建 Node 节点
            // 成功则退出循环,失败再次自旋走其他逻辑
            if (casTabAt(tab, i, null,
                         new Node<K,V>(hash, key, value, null)))
                break;                   // no lock when adding to empty bin
        }
        // 条件成立,表示当前桶位的头节点为 FWD 节点,表示目前 map 正处于扩容中..
        else if ((fh = f.hash) == MOVED)
            // 看到 fwd 节点后,当前节点有义务帮助当前 map 对象完成迁移数据的工作。
            tab = helpTransfer(tab, f);
        // 当前桶位可能是链表也可能是红黑树代理节点 treebin
        else {
            // 当插入 key 存在时,会将旧值赋值给 oldVal,并返回
            V oldVal = null;
            // 通过使用 sync 加锁“头节点”,理论上的头节点,因为下面会对是否为头节点做判断
            synchronized (f) {
                // 判断当前头尾的头节点是否为 之前获取的头节点
                // 避免其他线程将该桶位的头节点修改掉,导师当前线程 sync 加锁出问题
                if (tabAt(tab, i) == f) {
                    // 条件成立,说明当前桶位就是普通链表 
                    if (fh >= 0) {
                        //1. 当前插入 key 与链表当中所有元素的 key 都不一致时,当前的插入操作是追加到链表的末尾,binCount表示链表长度
                        //2. 当前插入 key 与链表中的某个元素的 key 不一致时,当前插入操作可能就是替换操作了。bingCount 表示冲突位置 (binCount - 1)
                        binCount = 1;
                        // 循环遍历 map
                        for (Node<K,V> e = f;; ++binCount) {
                            K ek;
                            // 如果 map 中某一桶位元素的 key 与当前要插入的 key 一致,替换
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                oldVal = e.val;
                                if (!onlyIfAbsent)
                                    e.val = value;
                                break;
                            }
                            // 前提:遍历 map 中的 key 与当前要插入元素的 key 不一致
                            // 1. 更新循环处理节点为 当前节点的下一个节点
                            // 2. 判断下一个节点是否为 null,如果是 null,说明当前节点已经是队尾了,插入数据需要追加到对尾节点的后面。
                            Node<K,V> pred = e;
                            if ((e = e.next) == null) {
                                pred.next = new Node<K,V>(hash, key,
                                                          value, null);
                                break;
                            }
                        }
                    }
                    //该桶位一定不是链表
                    //条件成立,当前桶位是红黑树代理节点 treeBin
                    else if (f instanceof TreeBin) {
                        Node<K,V> p;
                        // 将 binCount 设置为 2,后面 addCount() 有用到
                        binCount = 2;
                        // 成立,说明冲突了,返回引用
                        if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                       value)) != null) {
                            oldVal = p.val;
                            if (!onlyIfAbsent)
                                p.val = value;
                        }
                    }
                }
            }
            // 说明当前桶位不为 null,可能是红黑树也可能是链表
            if (binCount != 0) {
                // 如果 binCount >= 8 表示处理的桶位一定是链表
                if (binCount >= TREEIFY_THRESHOLD)
                    //树化操作
                    treeifyBin(tab, i);
                // 明当前线程插入的数据key,与原有k-v发生冲突,需要将原数据v返回给调用者。
                if (oldVal != null)
                    return oldVal;
                break;
            }
        }
    }
    //1.统计当前table一共有多少数据
    //2.判断是否达到扩容阈值标准,触发扩容。
    addCount(1L, binCount);
    return null;
}

初始化方法

private final Node<K,V>[] initTable() {
    // tab 表示 map.table 引用
    // sc 表示临时局部的 sizeCtl 的值
    Node<K,V>[] tab; int sc;
    // 当前散列表尚未初始化..
    while ((tab = table) == null || tab.length == 0) {
        if ((sc = sizeCtl) < 0)
            // < 0:要么当前 tbale 正在初始化(有其他线程创建 table 数组),当前线程需要自旋等待;
            //要么当前 table 数组正在扩容,当前线程参与并发扩容的数量  
            Thread.yield(); // lost initialization race; just spin
        /*
         * 条件成立:CAS 设置 sizeCtl = -1 成功
         * 1. sizeCtl = 0,表示创建 table 数组时使用 DEFAULT_CAPCITY 为大小
         * 2. 如果 table 尚未初始化,表示初始化大小
         * 3. 如果 table 已经初始化,表示下次扩容时的触发条件(阈值)
         */
        else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
            try {
                // 这里又判断一遍目的:防止其他线程已经初始化完毕,然后当前线程再次初始化
                // 条件成立,说明其他线程都没有进入过这个 if 块,当前线程就是具备初始化table 的权利
                if ((tab = table) == null || tab.length == 0) {
                    // 设置数组大小
                    int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
                    @SuppressWarnings("unchecked")
                    Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
                    // 最终赋值给 map.table
                    table = tab = nt;
                    // n>>>2 等于 1/4 n。sc = 3/4 n = 0.75*n 表示下一次扩容触发条件(阈值)
                    sc = n - (n >>> 2);
                }
            } finally {
                // 如果当前线程是第一次创建 map.table 的线程的话,sc 表示的是 下一次扩容的阈值
                // 如果不是第一次创建 map.table,当前线程进入到 else if 块时,
                // 将sizeCtl 设置为 -1,那么这时,需要将其修改为 进入时的值。
                sizeCtl = sc;
            }
            break;
        }
    }
    return tab;
}

stride 表示分配给线程任务的步长,这是什么意思呢?用白话解释一下:首先我们知道如果扩容了要重新计算原来数组元素的下标。如果一个一个的去计算,太慢了。所以设计一个区间一个区间地去计算,这样就快了。那么这个区间就是步长。那么步长肯定有一个界限,在源码里用 i 表示当前线程执行的桶位(倒着来的,如当前数组长度是 16 那么 i 就在 15号开始),bound 表示步长下界(如果步长是 5 那么它就是 10)。 扩容线程总体流程:

  1. 判断当前线程是不是触发扩容的线程 if 是:当前线程创建新表 否:走下一步
  2. 分配任务区间 if 分配成功:那么就更新任务下标 -> 迁移数据(如果没有迁移完毕就一直迁移,迁移成功就重新分配任务区间) if 分配失败:判断当前线程是不是最后一个退出的
  3. if 不是最后一个退出:退出扩容方法 if 是:那么就检查一下是不是任务都完成了
  4. if 任务都完成了:退出方法 if 没完成 判断是不是 fwd 节点:是:更新任务下标 否:迁移数据

JDK1.8 ConcurrentHashMap并发扩容.png

扩容方法

private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
    // n 表示扩容之前 table 数组的长度
    // stride 表示分配给线程任务的步长
    int n = tab.length, stride;
    // 计算步长,根据 cpu 去计算,但看源码没必要,就认为他是固定的 16 就可以了
    if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
        stride = MIN_TRANSFER_STRIDE; // subdivide range
    // 条件成立:表示当前线程为触发本次扩容的线程。
    // 条件不成立:表示当前线程是协助扩容的线程
    if (nextTab == null) {            // initiating
        try {
            // 创建一个比原数组大一倍的数组
            @SuppressWarnings("unchecked")
            Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
            nextTab = nt;
        } catch (Throwable ex) {      // try to cope with OOME
            sizeCtl = Integer.MAX_VALUE;
            return;
        }
        //新表
        nextTable = nextTab;
        //记录迁移数据整体位置的一个标记。index 计数是从 1 开始的。
        transferIndex = n;
    }
    // 表示新数组的长度
    int nextn = nextTab.length;
    // FWD 节点,当某个桶位数据处理完毕后,将此桶位设置成 FWD 节点,
    // 其他写线程或者读线程看到后会有不同逻辑。
    ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
    // 推进标记
    boolean advance = true;
    // 完成标记
    boolean finishing = false; // to ensure sweep before committing nextTab
    // i 表示分配给当前线程任务,执行到的桶位
    // bound 表示分配给当前线程任务的下界限制
    for (int i = 0, bound = 0;;) {
        // f 桶位头节点,fh 表示桶位头节点 hash 值
        Node<K,V> f; int fh;
        
        /*
         * 这个循环做了什么事情呢?
         * 1. 给当前线程分配任务区间
         * 2. 维护当前线程任务进度 (i 表示当前处理的桶位)
         * 3. 维护 map 对象全局范围内的进度
         */
        while (advance) {
            int nextIndex, nextBound;
            // 条件1 成立:表示当前线程任务尚未完成,还有相应的区间的桶位要处理,
            // --i 就让当前线程处理下一个桶位。
            // 不成立:表示当前线程任务已完成或未分配
            if (--i >= bound || finishing)
                advance = false;
            // 前置条件:表示当前线程任务已完成或未分配
            // 条件成立:表示对象全局范围内的桶位都分配完毕了,没有区间可以分配了,
            // 设置当前线程的 i 变量为 -1 跳出循环后,执行退出迁移任务相关程序
            else if ((nextIndex = transferIndex) <= 0) {
                i = -1;
                advance = false;
            }
            // 前置条件:1.当前线程需要分配任务区间 2.全局范围内还有桶位尚未迁移
            // 条件成立:说明给当前线程分配任务成功
            else if (U.compareAndSwapInt
                     (this, TRANSFERINDEX, nextIndex,
                      nextBound = (nextIndex > stride ?
                                   nextIndex - stride : 0))) {
                bound = nextBound;
                i = nextIndex - 1;
                advance = false;
            }
        }
        // i < 0:表示当前线程未分配到任务
        if (i < 0 || i >= n || i + n >= nextn) {
            int sc;
            if (finishing) {
                nextTable = null;
                table = nextTab;
                // n << 1 = 2 * n,n >>> 1 = n / 2
                // (n << 1) - (n >>> 1) = 2n - n / 2 = 3n / 2 = 1.5n = 2n * 0.75
                // 即 下次扩容阈值(我去,大神的思维我真不懂)
                sizeCtl = (n << 1) - (n >>> 1);
                return;
            }
            if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                    return;
                finishing = advance = true;
                i = n; // recheck before commit
            }
        }
        // 来到下面的逻辑前置条件: 当前任务尚未处理完,正在进行中
        
        // 条件成立:说明当前桶位未存放数据,只需要将此处设置为 fwd 节点即可
        else if ((f = tabAt(tab, i)) == null)
            advance = casTabAt(tab, i, null, fwd);
        // 条件成立:说明当前桶位已经迁移过了,不用处理了,
        else if ((fh = f.hash) == MOVED)
            advance = true; // already processed
        // 当前桶位有数据,而且 node 不是 fwd节点,都是需要迁移的
        else {
            // 锁定当前桶位的头节点
            synchronized (f) {
                // 怕锁错了,被其他人抢先了
                if (tabAt(tab, i) == f) {
                    // ln:低位链表引用
                    // hn: 高位链表引用
                    // 这里聊一下高位低位。当扩容后我们肯定也要讲链表重新计算桶位
                    // 那么通过计算就会将链表元素分为高位(首位1)和低位(首位 0)
                    // 这样链表就打散了,低位还是原来桶位号,高位去计算后新的桶位
                    Node<K,V> ln, hn;
                    // 条件成立:表示当前桶位是链表
                    // 接下来过程太恶心了,简写吧
                    if (fh >= 0) {
                        int runBit = fh & n;
                        Node<K,V> lastRun = f;
                        for (Node<K,V> p = f.next; p != null; p = p.next) {
                            int b = p.hash & n;
                            if (b != runBit) {
                                runBit = b;
                                lastRun = p;
                            }
                        }
                        // 低位链表成型
                        if (runBit == 0) {
                            ln = lastRun;
                            hn = null;
                        }
                        // 高位链表成型
                        else {
                            hn = lastRun;
                            ln = null;
                        }
                        for (Node<K,V> p = f; p != lastRun; p = p.next) {
                            int ph = p.hash; K pk = p.key; V pv = p.val;
                            if ((ph & n) == 0)
                                ln = new Node<K,V>(ph, pk, pv, ln);
                            else
                                hn = new Node<K,V>(ph, pk, pv, hn);
                        }
                        setTabAt(nextTab, i, ln);
                        setTabAt(nextTab, i + n, hn);
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                    // 表示当前桶位是红黑树代理 treeBin
                    else if (f instanceof TreeBin) {
                        // 头节点转换为 teebin
                        TreeBin<K,V> t = (TreeBin<K,V>)f;
                        //h:高,l:低(又来了,我吐了)
                        // 链表的头和尾
                        TreeNode<K,V> lo = null, loTail = null;
                        TreeNode<K,V> hi = null, hiTail = null;
                        int lc = 0, hc = 0;
                        // 循环 treebin 中的双向链表
                        for (Node<K,V> e = t.first; e != null; e = e.next) {
                            // h 处理当前元素的 hash值
                            int h = e.hash;
                            // 使用当前节点构建出来的
                            TreeNode<K,V> p = new TreeNode<K,V>
                                (h, e.key, e.val, null, null);
                            // 表示当前节点属于低位链节点
                            // 高低位链表采用尾插法
                            if ((h & n) == 0) {
                                if ((p.prev = loTail) == null)
                                    lo = p;
                                else
                                    loTail.next = p;
                                loTail = p;
                                ++lc;
                            }
                            // 表示当前节点属于高位链节点
                            else {
                                if ((p.prev = hiTail) == null)
                                    hi = p;
                                else
                                    hiTail.next = p;
                                hiTail = p;
                                ++hc;
                            }
                        }
                        // 低位链变:判断当前链表节点是否小于等于 6,
                        // 成立则从 treebin 双向链表转化为 Node 类型的单向链表
                        ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                            (hc != 0) ? new TreeBin<K,V>(lo) : t;
                        hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                            (lc != 0) ? new TreeBin<K,V>(hi) : t;
                        setTabAt(nextTab, i, ln);
                        setTabAt(nextTab, i + n, hn);
                        setTabAt(tab, i, fwd);
                        advance = true;
                    }
                }
            }
        }
    }
}

get 方法

    public V get(Object key) {
        //tab 引用map.table
        //e 当前元素
        //p 目标节点
        //n table数组长度
        //eh 当前元素hash
        //ek 当前元素key
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        //条件一:(tab = table) != null
        //true->表示已经put过数据,并且map内部的table也已经初始化完毕
        //false->表示创建完map后,并没有put过数据,map内部的table是延迟初始化的,只有第一次写数据时会触发创建逻辑。
        //条件二:(n = tab.length) > 0 true->表示table已经初始化
        //条件三:(e = tabAt(tab, (n - 1) & h)) != null
        //true->当前key寻址的桶位 有值
        //false->当前key寻址的桶位中是null,是null直接返回null
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            //比较要查找元素和桶位元素 hash 值,一样则返回,不一样走下面逻辑
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            //条件成立:
            //1.-1  fwd 说明当前table正在扩容,且当前查询的这个桶位的数据 已经被迁移走了
            //2.-2  TreeBin节点,需要使用TreeBin 提供的find 方法查询。
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            // 桶位形成链表情况
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }
/*
 * 我们来看一下 eh < 0 的情况
 * 先说一下 fwd 节点的情况,treeBin 的后面会讲到
 */
 static final class ForwardingNode<K,V> extends Node<K,V> {
    final Node<K,V>[] nextTable;
    ForwardingNode(Node<K,V>[] tab) {
        super(MOVED, null, null, null);
        this.nextTable = tab;
    }

    Node<K,V> find(int h, Object k) {
        // loop to avoid arbitrarily deep recursion on forwarding nodes
        outer: for (Node<K,V>[] tab = nextTable;;) {
            Node<K,V> e; int n;
            if (k == null || tab == null || (n = tab.length) == 0 ||
                // true -> 1. 原来该桶位就是null
                //      -> 2. 后来被设置为空了
                (e = tabAt(tab, (n - 1) & h)) == null)
                return null;
            for (;;) {
                // eh 和 ek 都是新表中的元素
                int eh; K ek;
                // 如果要查找的元素与桶位元素一致,返回。
                if ((eh = e.hash) == h &&
                    ((ek = e.key) == k || (ek != null && k.equals(ek))))
                    return e;
                 
                if (eh < 0) {
                    if (e instanceof ForwardingNode) {
                        tab = ((ForwardingNode<K,V>)e).nextTable;
                        continue outer;
                    }
                    // eh < 0 还不是 fwd 节点,那么就是 treebin 了
                    else
                        return e.find(h, k);
                }
                // 链表
                if ((e = e.next) == null)
                    return null;
            }
        }
    }
}

remove 方法

public V remove(Object key) {
    // 找到对应 key 的元素后将其设置为 null,相当于删除。
    return replaceNode(key, null, null);
}

final V replaceNode(Object key, V value, Object cv) {
    int hash = spread(key.hashCode());
    for (Node<K,V>[] tab = table;;) {
        //f表示桶位头结点
        //n表示当前table数组长度
        //i表示hash命中桶位下标
        //fh表示桶位头结点 hash
        Node<K,V> f; int n, i, fh;
        // 如果 table 是空或者没有元素那么直接返回 null
        // 如果该元素没有在散列表中桶位是 null,那么也返回 null
        if (tab == null || (n = tab.length) == 0 ||
            (f = tabAt(tab, i = (n - 1) & hash)) == null)
            break;
        // 条件成立,说明当前 map 正在进行扩容,那么该线程帮忙干活
        else if ((fh = f.hash) == MOVED)
            tab = helpTransfer(tab, f);
        // 当前桶位正常且不是 null
        else {
            V oldVal = null;
            boolean validated = false;
            // 先锁住当前桶位的头节点
            synchronized (f) {
                if (tabAt(tab, i) == f) {
                    // fh > 0 表示当前元素时正常元素或者为链表
                    if (fh >= 0) {
                        validated = true;
                        for (Node<K,V> e = f, pred = null;;) {
                            K ek;
                            // 成功:说明循环的元素和所查的元素一致
                            if (e.hash == hash &&
                                ((ek = e.key) == key ||
                                 (ek != null && key.equals(ek)))) {
                                V ev = e.val;
                                if (cv == null || cv == ev ||
                                    (ev != null && cv.equals(ev))) {
                                    oldVal = ev;
                                    if (value != null)
                                        e.val = value;
                                    else if (pred != null)
                                        pred.next = e.next;
                                    else
                                        setTabAt(tab, i, e.next);
                                }
                                break;
                            }
                            pred = e;
                            if ((e = e.next) == null)
                                break;
                        }
                    }
                    // 当前节点为红黑树节点
                    //条件成立:TreeBin节点。
                    else if (f instanceof TreeBin) {
                        validated = true;

                        //转换为实际类型 TreeBin t
                        TreeBin<K,V> t = (TreeBin<K,V>)f;
                        //r 表示 红黑树 根节点
                        //p 表示 红黑树中查找到对应key 一致的node
                        TreeNode<K,V> r, p;

                        //条件一:(r = t.root) != null 理论上是成立
                        //条件二:TreeNode.findTreeNode 以当前节点为入口,向下查找key(包括本身节点)
                        //      true->说明查找到相应key 对应的node节点。会赋值给p
                        if ((r = t.root) != null &&
                            (p = r.findTreeNode(hash, key, null)) != null) {
                            //保存p.val 到pv
                            V pv = p.val;

                            //条件一:cv == null  成立:不必对value,就做替换或者删除操作
                            //条件二:cv == pv ||(pv != null && cv.equals(pv)) 成立:说明“对比值”与当前p节点的值 一致
                            if (cv == null || cv == pv ||
                                (pv != null && cv.equals(pv))) {
                                //替换或者删除操作


                                oldVal = pv;

                                //条件成立:替换操作
                                if (value != null)
                                    p.val = value;


                                //删除操作
                                else if (t.removeTreeNode(p))
                                    //这里没做判断,直接搞了...很疑惑
                                    setTabAt(tab, i, untreeify(t.first));
                            }
                        }
                    }
                }
            }
            // 如果锁错了对象,那么 validated 为 false,并进入下次自旋
            if (validated) {
                if (oldVal != null) {
                    if (value == null)
                        addCount(-1L, -1);
                    return oldVal;
                }
                break;
            }
        }
    }
    return null;
}

TreeBin

    static final class TreeBin<K,V> extends Node<K,V> {
        TreeNode<K,V> root;
        //链表的头节点
        volatile TreeNode<K,V> first;
        //等待者线程(当前lockState是读锁状态)
        volatile Thread waiter;
        /**
         * 1.写锁状态 写是独占状态,以散列表来看,真正进入到TreeBin中的写线程 同一时刻 只有一个线程。  
         *   lockState = 1
         * 2.读锁状态 读锁是共享,同一时刻可以有多个线程 同时进入到 TreeBin对象中获取数据。 
         *   每一个线程 都会给 lockStat + 4
         * 3.等待者状态(写线程在等待),当TreeBin中有读线程目前正在读取数据时,写线程无法修改数据,
         *   那么就将lockState的最低2位 设置为 0b 10
         */
        volatile int lockState;

        // values for lockState
        static final int WRITER = 1; // set while holding write lock
        static final int WAITER = 2; // set when waiting for write lock
        static final int READER = 4; // increment value for setting read lock
        static int tieBreakOrder(Object a, Object b) {
            int d;
            if (a == null || b == null ||
                (d = a.getClass().getName().
                 compareTo(b.getClass().getName())) == 0)
                d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                     -1 : 1);
            return d;
        }
        
        TreeBin(TreeNode<K,V> b) {
            //设置节点hash为-2 表示此节点是TreeBin节点
            super(TREEBIN, null, null, null);
            //使用first 引用 treeNode链表
            this.first = b;
            //r 红黑树的根节点引用
            TreeNode<K,V> r = null;

            //x表示遍历的当前节点
            for (TreeNode<K,V> x = b, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                //强制设置当前插入节点的左右子树为null
                x.left = x.right = null;
                //条件成立:说明当前红黑树 是一个空树,那么设置插入元素 为根节点
                if (r == null) {
                    //根节点的父节点 一定为 null
                    x.parent = null;
                    //颜色改为黑色
                    x.red = false;
                    //让r引用x所指向的对象。
                    r = x;
                }

                else {
                    //非第一次循环,都会来带else分支,此时红黑树已经有数据了

                    //k 表示 插入节点的key
                    K k = x.key;
                    //h 表示 插入节点的hash
                    int h = x.hash;
                    //kc 表示 插入节点key的class类型
                    Class<?> kc = null;
                    //p 表示 为查找插入节点的父节点的一个临时节点
                    TreeNode<K,V> p = r;

                    for (;;) {
                        //dir (-1, 1)
                        //-1 表示插入节点的hash值大于 当前p节点的hash
                        //1 表示插入节点的hash值 小于 当前p节点的hash
                        //ph p表示 为查找插入节点的父节点的一个临时节点的hash
                        int dir, ph;
                        //临时节点 key
                        K pk = p.key;

                        //插入节点的hash值 小于 当前节点
                        if ((ph = p.hash) > h)
                            //插入节点可能需要插入到当前节点的左子节点 或者 继续在左子树上查找
                            dir = -1;
                        //插入节点的hash值 大于 当前节点
                        else if (ph < h)
                            //插入节点可能需要插入到当前节点的右子节点 或者 继续在右子树上查找
                            dir = 1;

                        //如果执行到 CASE3,说明当前插入节点的hash 与 当前节点的hash一致,会在case3 做出最终排序。最终
                        //拿到的dir 一定不是0,(-1, 1)
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        //xp 想要表示的是 插入节点的 父节点
                        TreeNode<K,V> xp = p;
                        //条件成立:说明当前p节点 即为插入节点的父节点
                        //条件不成立:说明p节点 底下还有层次,需要将p指向 p的左子节点 或者 右子节点,表示继续向下搜索。
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            //设置插入节点的父节点 为 当前节点
                            x.parent = xp;
                            //小于P节点,需要插入到P节点的左子节点
                            if (dir <= 0)
                                xp.left = x;

                                //大于P节点,需要插入到P节点的右子节点
                            else
                                xp.right = x;

                            //插入节点后,红黑树性质 可能会被破坏,所以需要调用 平衡方法
                            r = balanceInsertion(r, x);
                            break;
                        }
                    }
                }
            }
            //将r 赋值给 TreeBin对象的 root引用。
            this.root = r;
            assert checkInvariants(root);
        }

结语

几乎源码都更新完了 很累,心碎想睡觉。其实没必要这么卷,如果为了面试可以看我上一篇文章。写的也很好。

站在巨人肩膀上

笔记来自于 B 站小刘讲源码。很好的老师,大家可以报名去看看。