结构
与 HashMap 类似,使用数组 + 链表 + 红黑树存储键值对

成员变量
transient volatile Node
private transient volatile Node
private static final int MIN_TRANSFER_STRIDE = 16 // 扩容线程每次最少要迁移16 个 hash 桶,在扩容中,参与的单个线程允许处理的最少 table 桶首节点个数,虽然适当添加线程,会使得整个扩容过程变快,但需要考虑多线程内存同时分配的问题
private transient volatile int sizeCtl;
默认为 0
-1 表示正在初始化
-(1+number) 表示有 number 个线程同时在扩容,线程必须竞争到这个共享变量,才能进行初始化或者扩容。
正数, table 中元素数量阈值,超过这个阈值就会扩容

static final int MOVED = -1; // ForwardingNode 的 hash 值,为 -1- ForwardingNode,在扩容时使用,如果 index 处 Node 节点 hash 值为 -1,表示正在扩容。
static final int TREEBIN = -2; // 树节点的 Hash 值
static final int RESERVED = -3; // 临时保留的 Hash 值
static final int HASH_BITS = 0x7fffffff; // usable bits of normal
哈希桶 Table 初始化
根据共享变量 sizeCtl 的值来决定是否由当前线程执行初始化操作(单线程进行初始化),若 sizeCtl < 0 表示正在扩容,该线程需要等待。
sizeCtl 为正数时,表示 table 的阈值(= 0.75*n),元素个数超过这个值将会扩容。
private final Node<K,V>[] initTable() {Node<K,V>[] tab; int sc;while ((tab = table) == null || tab.length == 0) {// 如果共享变量 sizeCtl < 0,说明有其它线程正在初始化或者扩容,让出 CPU,让其它线程先执行完if ((sc = sizeCtl) < 0)Thread.yield(); // lost initialization race; just spin// CAS 方式获取到锁,那么由该线程进行初始化else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {try {// 将 table 赋值给 tab,判断 tab 是否已经初始化if ((tab = table) == null || tab.length == 0) {// sc = sizeCtl > 0 表示已经初始化,否则使用默认容量 16。int n = (sc > 0) ? sc : DEFAULT_CAPACITY;@SuppressWarnings("unchecked")Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];table = tab = nt;// sc = 0.75*n,sc 表示阈值sc = n - (n >>> 2);}} finally {sizeCtl = sc;}break;}}return tab;}
key 对应到哈希桶的过程
hash 过程与 HashMap 类似,只是多了与 HASH_BITS 进行位运算
HASH_BITS 除了首位是 0,剩下的都是 1,按位与,得正数(首位为0);它的作用就是为了让上面的 hash 值为正数
// index 表示桶的位置int index = spread(key.hashCode) & (length - 1)static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hashstatic final int spread(int h) {return (h ^ (h >>> 16)) & HASH_BITS;}
get 方法
key,value 都不能为 null,key 为 null 时抛出 NullPointerException
将 key 进行 hash 然后找到数组位置处的索引 index
比较 Hash 值,并且若 index == key || equals 返回 true,直接返回 index 处元素
若 index 处的 hash 值小于 0,表示正在扩容,进一步调用 Node 子类的 find 方法
index 处的 hash 值不小于 0,通过链表 Next 指针遍历查找
static final int TREEBIN = -2; // hash for roots of treespublic V get(Object key) {Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;// 计算 hash 值int h = spread(key.hashCode());// 数组不为空 && 数组长度大于 0 && 该位置已经有元素if ((tab = table) != null && (n = tab.length) > 0 && (e = tabAt(tab, (n - 1) & h)) != null) {// 如果 key 的 hash 值一样,则进一步判断if ((eh = e.hash) == h) {// 如果是同一个 key 或者 equal 方法返回 trueif ((ek = e.key) == key || (ek != null && key.equals(ek)))// 返回对应 valuereturn e.val;}// 如果 hash 值小于 0,表示数组正在扩容// 此处 Node 节点为 ForwardingNode,调用 ForwardingNode 的 find 方法else if (eh < 0)return (p = e.find(h, key)) != null ? p.val : null;// eh > 0 情况,链表遍历while ((e = e.next) != null) {if (e.hash == h &&((ek = e.key) == key || (ek != null && key.equals(ek))))return e.val;}}// 没有元素return null;}
ForwardingNode 介绍
ForwardingNode 是 Node 子类之一,当节点的 Hash 值为 -1 时,该节点就为 ForwardingNode ,标记此处正在扩容
- 外层循环用于刷新 ForwardingNode 所在的 table 情况,因为扩容过程中 table 的节点情况在变化
- 内层循环则去以 next 指针的形式遍历 table,直到找到 hashCode 相同 && (== || equals )返回 true 的节点
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 nodesouter: for (Node<K,V>[] tab = nextTable;;) {Node<K,V> e; int n;// 先判断 nullif (k == null || tab == null || (n = tab.length) == 0 ||(e = tabAt(tab, (n - 1) & h)) == null)return null;for (;;) {int eh; K ek;// 若 Hash 值相同进一步判断变量是否相同,之间返回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;}elsereturn e.find(h, k); // 链表形式遍历}if ((e = e.next) == null)return null;}}}}
put 方法
table 为 null 或者 tab.size = 0,进行初始化
key 进行 hash 之后取模得到的索引位置,若在桶的位置元素为 null,那么直接插入元素。
桶位置元素不为 null,那么进行比较
判断 key 是否相同:
- 如果 key 相同,e 保存该节点
- 如果 key 不同,如果该是红黑树节点,那么执行红黑树的 put 方法;如果是链表节点,执行链表遍历操作,找到对应的节点并用 e 保存,如果链表长度大于 >=7,就将链表转为红黑树
Node e 保存找到的节点,如果没有找到返回 null
如果 size 超过阈值,进行扩容
public V put(K key, V value) {return putVal(key, value, false);}final V putVal(K key, V value, boolean onlyIfAbsent) {// key value 均不能为 nullif (key == null || value == null) throw new NullPointerException();int hash = spread(key.hashCode());int binCount = 0;// 获取当前 table,进入死循环,直至插入成功for (Node<K,V>[] tab = table;;) {Node<K,V> f; int n, i, fh;// 为空初始化数组if (tab == null || (n = tab.length) == 0)tab = initTable();// 索引所在位置没有元素,通过 casTabAt 方法插入元素并跳出循环else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value, null))){break; // no lock when adding to empty bin}}// 索引位置处是 ForwardingNode,该线程帮助扩容else if ((fh = f.hash) == MOVED)tab = helpTransfer(tab, f);// 该位置处节点为 普通节点,锁住该链表头结点并在尾部添加节点else {V oldVal = null;synchronized (f) {// 加锁之后,再判断索引位置处 key 是否相同if (tabAt(tab, i) == f) {// hash >= 0,通过链表遍历方式找到并替换节点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;}}}// index 处索引小于 0 (hash = -2 TREEBIN),并且是树节点,执行树的插入方法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;}}}}// binCount != 0 说明向链表或者红黑树中添加或修改一个节点成功// binCount == 0 说明 put 操作将一个新节点添加成为某个桶的首节点if (binCount != 0) {// >= 8 执行转红黑树的操作if (binCount >= TREEIFY_THRESHOLD)treeifyBin(tab, i);// oldVal != null 说明此次操作是修改操作,直接返回旧值,无需下面扩容检查if (oldVal != null)return oldVal;break;}}}// 判断是否需要扩容addCount(1L, binCount);return null;}
helpTransfer 帮助扩容
// 返回二进制最高位到第一个非 0 数字之间 0 的个数static final int resizeStamp(int n) {return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1));}// 帮助扩容final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {Node<K,V>[] nextTab; int sc;// tab != null && ForwardingNode && ForwardingNode.nextTable != nullif (tab != null && (f instanceof ForwardingNode) &&(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {// 生成标志位 rsint rs = resizeStamp(tab.length);while (nextTab == nextTable && table == tab &&(sc = sizeCtl) < 0) {// 如果 sizeCtl 无符号右移 16 位与上面标志位不同// 或者 sizeCtl == rs + 1 (扩容结束了,不再有线程进行扩容)// 或者 sizeCtl == rs + 65535 (如果达到最大帮助线程的数量,即 65535)// 或者转移下标正在调整 (扩容结束)// 结束循环if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||sc == rs + MAX_RESIZERS || transferIndex <= 0)break;// 以上情况不满足, sizeCtl++ ,增加一个线程进行扩容if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {// 复制或者移动 bins 里面的 Node 到新的 tabletransfer(tab, nextTab);break;}}return nextTab;}return table;}// 移动或者复制 Node 到新的 tableprivate final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {int n = tab.length, stride;// 计算单个线程允许处理的最少 table 桶首节点个数,不能小于 16if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)stride = MIN_TRANSFER_STRIDE; // subdivide range// 如果刚开始扩容,就初始化 nextTab,长度为原来的两倍if (nextTab == null) { // initiatingtry {@SuppressWarnings("unchecked")Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];nextTab = nt;} catch (Throwable ex) { // try to cope with OOMEsizeCtl = Integer.MAX_VALUE;return;}nextTable = nextTab;// transferIndex 指向最后一个桶,方便从后向前遍历transferIndex = n;}int nextn = nextTab.length;// 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;;) {Node<K,V> f; int fh;while (advance) {int nextIndex, nextBound;if (--i >= bound || finishing)advance = false;// transferIndex 本来指向最后一个桶,小于等于 0 说明处理完成else if ((nextIndex = transferIndex) <= 0) {i = -1;advance = false;}// 更新 transferIndex,处理的桶区间为 (nextBound,nextIndex)else if (U.compareAndSwapInt(this, TRANSFERINDEX, nextIndex,nextBound = (nextIndex > stride ?nextIndex - stride : 0))) {bound = nextBound;i = nextIndex - 1;advance = false;}}// 当前线程任务处理完成if (i < 0 || i >= n || i + n >= nextn) {int sc;if (finishing) {nextTable = null;table = nextTab;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}}// 索引位置为 null,设置 ForwardingNode 表示处理过else if ((f = tabAt(tab, i)) == null)advance = casTabAt(tab, i, null, fwd);// 该桶已经处理过else if ((fh = f.hash) == MOVED)advance = true; // already processedelse {// 锁住该桶synchronized (f) {// 再判断下桶有没有发生变化if (tabAt(tab, i) == f) {Node<K,V> ln, hn;if (fh >= 0) { // 普通的 Node 节点int runBit = fh & n; // 移动步长,为 0 或者 NNode<K,V> lastRun = f;// 整个 for 循环为了找到整个桶中最后连续的 fh & n 不变的结点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;}// 如果 fh&n 不变的链表的 runbit 都是 0,则 nextTab[i] 内元素 ln 前逆序,ln 及其之后顺序// 否则,nextTab[i+n]内元素全部相对原table逆序// 这是通过一个节点一个节点的往 nextTab 添加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);elsehn = new Node<K,V>(ph, pk, pv, hn);}// 把两条链表整体迁移到 nextTab 中setTabAt(nextTab, i, ln);setTabAt(nextTab, i + n, hn);// 将原桶标识位已经处理setTabAt(tab, i, fwd);advance = true;}// 红黑树的复制算法else if (f instanceof TreeBin) {TreeBin<K,V> t = (TreeBin<K,V>)f;TreeNode<K,V> lo = null, loTail = null;TreeNode<K,V> hi = null, hiTail = null;int lc = 0, hc = 0;for (Node<K,V> e = t.first; e != null; e = e.next) {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;elseloTail.next = p;loTail = p;++lc;}else {if ((p.prev = hiTail) == null)hi = p;elsehiTail.next = p;hiTail = p;++hc;}}// 节点数不够时退化为链表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;}}}}}}
- sizeCtl == rs + 1 扩容结束了,不再有线程进行扩容,这个判断可以在 addCount 方法中找到答案:默认第一个线程设置 sc == rs 左移 16 位 + 2,当第一个线程结束扩容了,就会将 sc 减一。这个时候,sc 就等于 rs + 1。
如果 sizeCtl == 标识符 + 1 ,说明扩容结束了,没有必要再扩容了。
扩容时机
- addCount 方法判断节点数量是否达到阈值
- treeifyBin 转树操作时,当数组长度还未超过 64 时,先进行扩容
size()
主要是 sumCount 的实现,元素个数 = baseCount + counterCells[i].value
当插入或删除数据时,会通过 addCount() 方法以 CAS 方式更新 baseCount 的值,当 CAS 更新失败,会调用 fullAddCount 方法进而更新 counterCells 里面的值。
其中内部类 CounterCell 被 @Contended 注解修饰,是为了防止 伪共享。
缓存系统中是以缓存行(cache line)为单位存储的。缓存行是2的整数幂个连续字节,一般为32-256个字节。最常见的缓存行大小是64个字节。当多线程修改互相独立的变量时,如果这些变量共享同一个缓存行,就会无意中影响彼此的性能,这就是伪共享。
JDK 1.8 建议使用 mappingCount 方法(返回 long) 代替 size() 方法返回元素个数,因为元素的个数可能大于 int 表示的范围。
public int size() {long n = sumCount();return ((n < 0L) ? 0 :(n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :(int)n);}final long sumCount() {CounterCell[] as = counterCells; CounterCell a;long sum = baseCount;if (as != null) {for (int i = 0; i < as.length; ++i) {if ((a = as[i]) != null)sum += a.value;}}return sum;}@sun.misc.Contended static final class CounterCell {volatile long value;CounterCell(long x) { value = x; }}public long mappingCount() {long n = sumCount();return (n < 0L) ? 0L : n; // ignore transient negative values}
博客参考
并发编程——ConcurrentHashMap#helpTransfer() 分析
