ConcurrentHashMap重要的属性,无论是初始化哈希表,还是扩容 rehash 的过程,都是需要依赖这个关键属性
private transient volatile int sizeCtl;
首先分析哈希算法spread()方法
static final int spread(int h) { //
return (h ^ (h >>> 16)) & HASH_BITS; //hash值的高16位与低16位进行异或运算
}
一、get方法
public V get(Object key) {
Node[] tab; Node e, p; int n, eh; K ek;
int h = spread(key.hashCode()); //hash算法-->spread方法
//判断表是否不为null,且判断索引处是否为不为null
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) { //hash值相等
if ((ek = e.key) == key || (ek != null && key.equals(ek)))//且key值也相等
return e.val;//直接返回val值
}
//如果eh<0 说明这个节点在树上 直接寻找
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;
}
find(h,key)方法是Node类的内部方法
static class Node implements Map.Entry { //Node内部类
final int hash;
final K key;
volatile V val;
volatile Node next;
//find(h,key)方法
Node find(int h, Object k) {
Node e = this;
if (k != null) {
//进行循环遍历
do {
K ek;
if (e.hash == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
} while ((e = e.next) != null);
}
return null;
}
}
二、put方法
public V put(K key, V value) {
return putVal(key, value, false); //调用putVal方法
}
2.1 putVal()方法
final V putVal(K key, V value, boolean onlyIfAbsent) {
//key、value为null,都不能存储
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());//spread方法-->hash值
int binCount = 0;
//死循环 何时插入成功 何时跳出 CAS
for (Node[] tab = table;;) {
Node f; int n, i, fh;
if (tab == null || (n = tab.length) == 0) //table为null
tab = initTable(); //初始化
//根据hash值计算出在table里面的位置
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
//如果这个位置为null,直接放进去,使用CAS进行不需要加锁
if (casTabAt(tab, i, null,
new Node(hash, key, value, null)))
break; // no lock when adding to empty bin
}
//如果f的hash值为-1,说明当前f是ForwardingNode节点,意味有其它线程正在扩容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {// 在链表或者红黑树中追加节点
V oldVal = null;
synchronized (f) { //节点加锁
if (tabAt(tab, i) == f) {
if (fh >= 0) { //链表结构
binCount = 1;
for (Node 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 pred = e;
if ((e = e.next) == null) {//遍历,加入最后
pred.next = new Node(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {//红黑树结构
Node p;
binCount = 2;
if ((p = ((TreeBin)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
//如果链表长度已经达到临界值8 就需要把链表转换为树结构
if (binCount >= TREEIFY_THRESHOLD)
// 这个方法和HashMap中稍微有一点点不同,那就是它不是一定会进行红黑树转换,
// 如果当前数组的长度小于64,那么会选择进行数组扩容,而不是转换为红黑树
treeifyBin(tab, i);//扩容或者转化红黑树
if (oldVal != null)
return oldVal;
break;
}
}
}
//将当前ConcurrentHashMap的元素数量+1
addCount(1L, binCount);
return null;
}
2.2 initTable()初始化
初始化方法主要应用了关键属性sizeCtl 如果这个值〈0,表示其他线程正在进行初始化,就放弃这个操作。在这也可以看出ConcurrentHashMap的初始化只能由一个线程完成。如果获得了初始化权限,就用CAS方法将sizeCtl置为-1,防止其他线程进入。初始化数组后,将sizeCtl的值改为0.75*n。
private final Node[] initTable() {
Node[] tab; int sc;
while ((tab = table) == null || tab.length == 0) { //表为null
if ((sc = sizeCtl) < 0) //表示有别的线程正在进行初始化
Thread.yield(); // lost initialization race; just spin //进入自旋状态
//否则利用CAS方法把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;
@SuppressWarnings("unchecked")
Node[] nt = (Node[])new Node[n];
table = tab = nt;
sc = n - (n >>> 2);//相当于0.75*n 设置一个扩容的阈值
}
} finally {
sizeCtl = sc;
}
break;//跳出初始化
}
}
return tab;
}
2.3 helpTransfer()方法
这是一个协助扩容的方法。这个方法被调用的时候,当前ConcurrentHashMap一定已经有了nextTable对象,首先拿到这个nextTable对象,调用transfer方法。回看上面的transfer方法可以看到,当本线程进入扩容方法的时候会直接进入复制阶段。
final Node[] helpTransfer(Node[] tab, Node f) {
Node[] nextTab; int sc;
//判断tab不为null且f节点为ForwardingNode类型并且要连接的table也不为null
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode)f).nextTable) != null) {
int rs = resizeStamp(tab.length);
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);// 去帮助执行transfer任务
break;
}
}
return nextTab;
}
return table;
}
2.4treeifyBin()方法
完成扩容或者转化红黑树
private final void treeifyBin(Node[] tab, int index) {
Node b; int n, sc;
if (tab != null) {
// MIN_TREEIFY_CAPACITY 为 64
// 如果table容量小于64,也就是16,32时候不会转化为红黑树,而是进行扩容处理。
if ((n = tab.length) < MIN_TREEIFY_CAPACITY)
tryPresize(n << 1);//扩容方法
//否则进行转化红黑树
else if ((b = tabAt(tab, index)) != null && b.hash >= 0) { //索引位置头节点
synchronized (b) {//加锁处理
if (tabAt(tab, index) == b) {//再一次判断节点是否相等
TreeNode hd = null, tl = null;
for (Node e = b; e != null; e = e.next) {
TreeNode p =
new TreeNode(e.hash, e.key, e.val,
null, null);//转化为红黑树节点
if ((p.prev = tl) == null)
hd = p;
else
tl.next = p;
tl = p;
}
// 将红黑树设置到数组相应位置中
setTabAt(tab, index, new TreeBin(hd));
}
}
}
}
}
三、tryPresize()方法 --->扩容操作
扩容也是做翻倍扩容的,扩容后数组容量为原来的 2 倍
private final void tryPresize(int size) {
int c = (size >= (MAXIMUM_CAPACITY >>> 1)) ? MAXIMUM_CAPACITY :
tableSizeFor(size + (size >>> 1) + 1);
int sc;
while ((sc = sizeCtl) >= 0) { //大于等于0,说明没有线程在扩容
Node[] tab = table; int n;
if (tab == null || (n = tab.length) == 0) { //判断表是否为null
n = (sc > c) ? sc : c;
//利用CAS方法把sizectl的值置为-1 表示本线程正在进行初始化
if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
if (table == tab) {
@SuppressWarnings("unchecked")
Node[] nt = (Node[])new Node[n];
table = nt;
sc = n - (n >>> 2);//0.75*n
}
} finally {
sizeCtl = sc;//设置成阈值大小
}
}
}
else if (c <= sc || n >= MAXIMUM_CAPACITY) //大于等于最大容量
break; //直接结束循环
else if (tab == table) {
int rs = resizeStamp(n);
if (sc < 0) { //正在扩容处理
Node[] nt;
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))
transfer(tab, nt);//transfer迁移数据
}
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + 2))
transfer(tab, null);
}
}
}
特别的节点ForwardingNode
static final class ForwardingNode extends Node {
final Node[] nextTable; //连接下一个table
ForwardingNode(Node[] tab) {
super(MOVED, null, null, null);//K、V、next皆为null,hash值为-1
this.nextTable = tab;
}
Node find(int h, Object k) {
// loop to avoid arbitrarily deep recursion on forwarding nodes
outer: for (Node[] tab = nextTable;;) {
Node e; int n;
if (k == null || tab == null || (n = tab.length) == 0 ||
(e = tabAt(tab, (n - 1) & h)) == 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) {
tab = ((ForwardingNode)e).nextTable;
continue outer;
}
else
return e.find(h, k);
}
if ((e = e.next) == null)
return null;
}
}
}
}