分段锁顾名思义就是只锁一段而不是全局的加锁,有效提高了在多线程情况下的速度
ConcurrentHashMap之所以效率高又是线程安全的,主要是使用了分段锁和cas,很多文章都有不细说了
使用了分段锁的代码段:
//这里锁的就是数组中的单向链表或红黑树的头结点,put时hash到不同的数组中的链表锁的对象是不同的可以实现并行put,只有被分配到同一个链表的时候需要阻塞
synchronized (f) {
if (tabAt(tab, i) == f) {
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;
}
}
}
//添加到树中
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;
}
}
}
}
//转为树
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
LongAdder是在1.8之后才新加入juc里的工具,里面有一个cell数组,cell是在Striped64中的静态内部类,每个cell维护自己的value,AtomicInteger中仅维护一个全局的value,调用sum将所有cell的value和base相加就是最终的值
先看一下Add方法
public void add(long x) {
Cell[] as; long b, v; int m; Cell a;
//如果cell是空未被初始化
//就执行!casBase(b = base, b + x)
//这里的base就相当于AtomicInteger中全局的value
//cas设置成功就结束,设置失败说明有竞争,进入方法体
if ((as = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;
//做了一些判断
if (as == null || (m = as.length - 1) < 0 ||
(a = as[getProbe() & m]) == null ||
//cas设置cell的value值,如果设置是失败进入方法体
//uncontended会变为false
!(uncontended = a.cas(v = a.value, v + x)))
longAccumulate(x, null, uncontended);
}
}
下面就是核心的方法
final void longAccumulate(long x, LongBinaryOperator fn,
boolean wasUncontended) {
int h;
if ((h = getProbe()) == 0) {
ThreadLocalRandom.current(); // force initialization
h = getProbe();
wasUncontended = true;
}
boolean collide = false; // True if last slot nonempty
for (;;) {
Cell[] as; Cell a; int n; long v;
if ((as = cells) != null && (n = as.length) > 0) {
//坑里是空的话
if ((a = as[(n - 1) & h]) == null) {
//cellsBusy 0代表可以获取锁
if (cellsBusy == 0) { // Try to attach new Cell
//把add的值放入cell的value中
Cell r = new Cell(x); // Optimistically create
//cellsBusy 锁标识位如果是0 并且cas将0改为1成功的话
if (cellsBusy == 0 && casCellsBusy()) {
boolean created = false;
try { // Recheck under lock
Cell[] rs; int m, j;
if ((rs = cells) != null &&
(m = rs.length) > 0 &&
rs[j = (m - 1) & h] == null) { //一顿判断之后把cell放入坑里
rs[j] = r;
//结束表示位
created = true;
}
} finally {
//释放锁
cellsBusy = 0;
}
if (created)
break;
//如果坑不够了,或者坑里有人了就继续循环跳到下面扩容的代码段,扩容完不会直接丢进去需要再次循环进到上面这个代码段里
continue; // Slot is now non-empty
}
}
collide = false;
}
else if (!wasUncontended) // CAS already known to fail
wasUncontended = true; // Continue after rehash
else if (a.cas(v = a.value, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break;
else if (n >= NCPU || cells != as)
collide = false; // At max size or stale
else if (!collide)
collide = true;
else if (cellsBusy == 0 && casCellsBusy()) {
try {
if (cells == as) { // Expand table unless stale //扩容2倍
Cell[] rs = new Cell[n << 1];
//n是原始cell数组长度,按原始下表移动到新数组
for (int i = 0; i < n; ++i)
rs[i] = as[i];
cells = rs;
}
} finally {
cellsBusy = 0;
}
collide = false;
continue; // Retry with expanded table
}
h = advanceProbe(h);
}
//获取锁
else if (cellsBusy == 0 && cells == as && casCellsBusy()) {
boolean init = false;
try { // Initialize table
if (cells == as) {
//初始化为2的整数倍
Cell[] rs = new Cell[2];
rs[h & 1] = new Cell(x);
cells = rs;
init = true;
}
} finally {
//释放锁
cellsBusy = 0;
}
if (init)
break;
}
else if (casBase(v = base, ((fn == null) ? v + x :
fn.applyAsLong(v, x))))
break; // Fall back on using base
}
}