ConcurrentHashMap 源码全解二
红黑树实现讲解
红黑树是一种特殊的平衡二叉树,通过红黑两种颜色来限制每个节点的左右子节点的高度差不超过 2 倍,这就要求在添加或删除元素的时候,必须进行调整来保持这样的限制,从而实现自我平衡。下面我们就来看看 ConcurrentHashMap 对于红黑树的源码实现
红黑树的特性:
1、每个节点或者是黑色,或者是红色。
2、根节点是黑色。
3、每个叶子节点(NIL)是黑色。 [注意:这里叶子节点,是指为空(NIL或NULL)的叶子节点!]
4、如果一个节点是红色的,则它的子节点必须是黑色的。
5、从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点
static final class TreeBin<K,V> extends Node<K,V> {
TreeNode<K,V> root;
volatile TreeNode<K,V> first;// 用于链表查找
volatile Thread waiter;
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
TreeBin(TreeNode<K,V> b) {
super(TREEBIN, null, null, null); // 调用 Node 节点构造函数,注意传入的 hash 值等于 TREEBIN = -2 是一个负数
this.first = b; // 保存 first 节点 为 传入的 TreeNode 节点,注意此时 TreeNode 是一个双向链表
TreeNode<K,V> r = null;
for (TreeNode<K,V> x = b, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next; // 取出 next 节点
x.left = x.right = null;
if (r == null) {
x.parent = null;
x.red = false;
r = x; // root 根节点不保存数据
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = r;;) {
int dir, ph;// dir 用于表示当前节点是要作为 左节点插入 还是有节点插入
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;//表示应该作为 左节点插入
else if (ph < h)
dir = 1;//表示应该作为 右节点插入
else if ((kc == null &&// 如果上述条件没有判断出是左节点还是有节点,那么查看 key 是否实现了 Comparable 接口,然后通过 compareTo 方法进行比较大小,还是没有比较出大小,则调用 tieBreakOrder 方法完成大小比较操作
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
// 循环找到插入的位置,根据 dir 决定是左节点还是有节点
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp; // 设置插入节点的 parent 节点
if (dir <= 0)
xp.left = x;
else
xp.right = x;
r = balanceInsertion(r, x);
break;
}
}
}
}
this.root = r;
assert checkInvariants(root);
}
}
balanceInsertion 方法
为了满足红黑树的特性,在数据插入红黑树后,需要对其进行调整以满足限制,进行 左旋或右旋操作,下面我们先来看一个插入示例,原始红黑树如下图,
第一步 插入数字 56 后变为下图模样,不满足红黑树特性,需要进行变色和旋转调整
插入后我们发现节点 60 的左节点深度大于右节点深度的 2 倍了,需要旋转操作来进行调整,首先进行 左旋操作(节点 56 进行),结果如下
左旋完成后还是不满足红黑树要求,再次进行右旋操作,然后在进行颜色调整,结果如下,满足红黑树要求
// root 红黑树的根节点,x 插入节点
static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root, TreeNode<K,V> x) {
x.red = true;// 默认插入节点是 红色 节点
// xp:x节点的父节点;xpp:xp节点的父节点(也即x.parent.parent);
// xppl:x.parent.parent.left 左节点
// xppr:x.parent.parent.right 右节点
// 此 for 循环作用:完成节点颜色调整及左旋或右旋以满足红黑树特性
for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
if ((xp = x.parent) == null) {// x.parent == null 表明自己成为了 根节点,设置为 黑色节点
x.red = false;
return x;
}
// x的父节点是黑色节点或x.parent.parent == null 说明当前红黑树满足红黑树的特性,无需对其进行调整(根节点无需变更)
else if (!xp.red || (xpp = xp.parent) == null)
return root;
if (xp == (xppl = xpp.left)) {// x 节点在左链上,是 xp 的左节点或右节点
if ((xppr = xpp.right) != null && xppr.red) {// 更新节点颜色
xppr.red = false;
xp.red = false;
xpp.red = true;
x = xpp;// 更新 x 节点引用,重复循环检测红黑树状态是否满足其特性
}
else {
if (x == xp.right) {// 插入节点是在右子节点上
root = rotateLeft(root, x = xp);// 左旋操作
// 判断插入节点的parent.parent是否为空,获取最新 xpp 节点
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {// xp 不为空
xp.red = false; // 设置 xp 为黑色节点
if (xpp != null) {// 不为空,进行右旋操作
xpp.red = true;// 设置 xpp 为红色节点
root = rotateRight(root, xpp);
}
}
}
}
// 下述原理同上
else {
if (xppl != null && xppl.red) {
xppl.red = false;
xp.red = false;
xpp.red = true;
x = xpp;
}
else {
if (x == xp.left) {
root = rotateRight(root, x = xp);
xpp = (xp = x.parent) == null ? null : xp.parent;
}
if (xp != null) {
xp.red = false;
if (xpp != null) {
xpp.red = true;
root = rotateLeft(root, xpp);
}
}
}
}
}
}
rotateLeft 方法
左旋操作,节点作为右子节点插入,参数介绍 root 根节点,p 插入节点的 parent 节点,r = p.right 右子节点,pp 是 p 的 parent 节点;
static <K,V> TreeNode<K,V> rotateLeft(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> r, pp, rl;
if (p != null && (r = p.right) != null) { // 节点 p 的 右节点必须不为空
if ((rl = p.right = r.left) != null) // 节点 r.left 不为空,将 p.right 右节点 指向 r.left 节点
rl.parent = p; // 将 r.left 节点的 parent 指向 p
if ((pp = r.parent = p.parent) == null)// p的 parent 为空,表示 p 是根节点
(root = r).red = false;
else if (pp.left == p)
pp.left = r;
else
pp.right = r;
r.left = p;
p.parent = r;
}
return root;
}
rotateRight 方法
原理同 左旋
static <K,V> TreeNode<K,V> rotateRight(TreeNode<K,V> root,
TreeNode<K,V> p) {
TreeNode<K,V> l, pp, lr;
if (p != null && (l = p.left) != null) {
if ((lr = p.left = l.right) != null)
lr.parent = p;
if ((pp = l.parent = p.parent) == null)
(root = l).red = false;
else if (pp.right == p)
pp.right = l;
else
pp.left = l;
l.right = p;
p.parent = l;
}
return root;
}
左右旋转总结:围绕当前节点、父节点以及父节点的父节点之间的right 、left、parent 之间引用的转换变更操作,自己多画图有利于理解
find 方法
final Node<K,V> find(int h, Object k) {
if (k != null) {
for (Node<K,V> e = first; e != null; ) {
int s; K ek;
// 此判断 为 ture 表明红黑树有线程持有写锁或有正在等待写锁的线程,此时通过链表的方式遍历查找
if (((s = lockState) & (WAITER|WRITER)) != 0) {
if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
e = e.next;
}
else if (U.compareAndSwapInt(this, LOCKSTATE, s, s + READER)) { // CAS 获取读锁
TreeNode<K,V> r, p;
try {
p = ((r = root) == null ? null : r.findTreeNode(h, k, null));
} finally {
Thread w;
if (U.getAndAddInt(this, LOCKSTATE, -READER) == (READER|WAITER) && (w = waiter) != null)
LockSupport.unpark(w);
}
return p;
}
}
}
return null;
}
findTreeNode 方法
查找方法很简单,比较父子节点的hash值大小,大于父节点找右子树,小于父节点找左子树
final TreeNode<K,V> findTreeNode(int h, Object k, Class<?> kc) {
if (k != null) {
// ((r = root) == null ? null : r.findTreeNode(h, k, null))
TreeNode<K,V> p = this; // 从当前节点开始查找,此处 p 等于 root 根节点
do {
int ph, dir; K pk; TreeNode<K,V> q;
TreeNode<K,V> pl = p.left, pr = p.right; // 获取 p 节点的左右子节点
if ((ph = p.hash) > h) // ph 大于 当前 h ,查找左子树
p = pl;
else if (ph < h)// ph 小于 当前 h ,查找右子树
p = pr;
else if ((pk = p.key) == k || (pk != null && k.equals(pk)))
return p; // 找到了,返回 p 节点
else if (pl == null) // 左子树为空,查找右子树
p = pr;
else if (pr == null) // 右子树为空,查找左子树
p = pl;
else if ((kc != null ||
(kc = comparableClassFor(k)) != null) &&
(dir = compareComparables(kc, k, pk)) != 0)
// 比父节点小 查找 左子树,比父节点大 查找 右子树
p = (dir < 0) ? pl : pr;
else if ((q = pr.findTreeNode(h, k, kc)) != null) // 没有实现 Comparable 接口,默认从右子树开始查找
return q;
else
p = pl; // 右子树没有找到,那么从左子树开始查找
} while (p != null);
}
return null;
}
get 方法
根据 key 获取 value
1、计算 hash 值
2、通过 hash 算出所在数组下标,通过 Unsafe 类取出下标处的值
3、比较该值是否是需要的值,通过 比较 hash 值 和 equals 方法进行比较,是,直接返回
4、获取到的 key 的 hash 值 小于 0 说明该节点是红黑树的头结点,调用 find 方法查找,此处暂不考虑通过 computeIfAbsent 方法放入的值
5、通过链表查找
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());// 1、根据 key 计算出 hash 值
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {// 2、获取到对应下标处的值
if ((eh = e.hash) == h) {// hash 值相同,说明是普通节点,那么比较 key 是否相同,相同直接返回 Value 值,不同,进一步比较 equals 方法
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
// hash 值小于 0 ,则可能是 MOVED、TREEBIN 或 RESERVED,调用 Node 的 find 方法查找
// 这三种状态分别对应 ForwardingNode 、TreeBin 、ReservationNode(该节点为计算时的占位节点,此处不做介绍)
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;
}
ForwardingNode#find 方法
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;
}
// 数组正在扩容,原数组找到的对应 solt 为 转移ForwardingNode节点
Node<K,V> find(int h, Object k) {
outer: for (Node<K,V>[] tab = nextTable;;) {// 获取目标数组对象
Node<K,V> e; int n;
if (k == null || tab == null || (n = tab.length) == 0 ||
(e = tabAt(tab, (n - 1) & h)) == null) // key 为空 或对应slot 为空,直接返回 null
return null;
for (;;) {
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) {
// 获取扩容后的最新数组,重新开始从外部循环开始遍历查找,如果没有这一步将会导致 下面 e.find 的递归,可能会导致栈溢出
tab = ((ForwardingNode<K,V>)e).nextTable;
continue outer;
}
else
return e.find(h, k);
}
if ((e = e.next) == null)
return null;
}
}
}
}