一 ConcurrentHashMap
- 支持并发访问的HashMap
- cas方式修改头节点,synchronized方式修改链表或红黑树节点
1.1 存储节点
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;//链表
}
1.2 查询
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());//计算节点索引(n - 1) & h
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;//hash一致且key一致,返回值
}
else if (eh < 0)//查询链表,有key一致的返回值,否则返回null
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;
}
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
1.3 赋值
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());//计算hash
int binCount = 0;
for (Node<K,V>[] tab = table;;) {//遍历存储数组
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();//初始化存储数组
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {//hash索引的数组元素为null
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))//cas初始化首节点
break; // no lock when adding to empty bin
}
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<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;//有相同key的,则修改值
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)//相同hash索引值超过8个节点
treeifyBin(tab, i);//转换为树结构
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
1.4 删除
final V replaceNode(Object key, V value, Object cv) {
int hash = spread(key.hashCode());//计算hash
for (Node<K,V>[] tab = table;;) {//遍历存储数组
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
break;//数组为空,或hash对应索引为null,直接跳出
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);//迁移中
else {
V oldVal = null;
boolean validated = false;
synchronized (f) {//加锁
if (tabAt(tab, i) == f) {
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)))) {//相同key
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;
}
}
else if (f instanceof TreeBin) {//红黑树删除节点
validated = true;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) {
V pv = p.val;
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));//存在空子树,则降为链表
}
}
}
}
}
if (validated) {
if (oldVal != null) {
if (value == null)
addCount(-1L, -1);//修改统计计数,数据迁移
return oldVal;
}
break;
}
}
}
return null;
}
1.5 节点统计
final long sumCount() {
CounterCell[] as = counterCells; CounterCell a;
long sum = baseCount;//首先在baseCount中cas修改统计计数
if (as != null) {//修改baseCount失败则修改CounterCell中统计计数
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;//节点总数所有的求和
}
1.6 数据迁移
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
//多核则节点总数/8*核数,单核则为节点总数
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)//一次迁移的数量,最小16
stride = MIN_TRANSFER_STRIDE; // subdivide range
if (nextTab == null) { //初始化迁移
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;//保存迁移目标数组
transferIndex = n;
}
int nextn = nextTab.length;
//初始化为hash值为moved的节点,表示该索引已迁移完成
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
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) {//迁移完成,更换存储table为新存储数组
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
}
}
else if ((f = tabAt(tab, i)) == null)//索引为null,赋值为迁移完成节点
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)//迁移完成
advance = true; // already processed
else {
synchronized (f) {
if (tabAt(tab, i) == f) {
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;
}
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;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.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);//按hash分割节点到高低两个索引里
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);//迁移完成, 设置为迁移完成节点
advance = true;
}
}
}
}
}
}
二 ConcurrentLinkedQueue
private static class Node<E> {
volatile E item;
volatile Node<E> next;
}
2.1 添加节点
public boolean offer(E e) {
checkNotNull(e);
final Node<E> newNode = new Node<E>(e);
for (Node<E> t = tail, p = t;;) {//从tail往后遍历,tail可能不是尾节点
Node<E> q = p.next;
if (q == null) {//找到尾节点了
// p is last node
if (p.casNext(null, newNode)) {//添加节点到尾节点
if (p != t) //tail不是真实的尾节点,则更新tail
casTail(t, newNode); //更新tail引用,允许失败。
return true;
}
// Lost CAS race to another thread; re-read next
}
else if (p == q)//异常,死循环。
p = (t != (t = tail)) ? t : head;
else
// tail变更了,重新从tail开始往后遍历
p = (p != t && t != (t = tail)) ? t : q;
}
}
2.2 队列节点出队
public E poll() {
restartFromHead:
for (;;) {
for (Node<E> h = head, p = h, q;;) {//从head节点遍历
E item = p.item;
//head可能不是真实的头节点,
//往后遍历直到收到item不为null的是真实头节点
if (item != null && p.casItem(item, null)) {//修改头节点item为null
if (p != h) // hop two nodes at a time
updateHead(h, ((q = p.next) != null) ? q : p);//更新head到真实头节点
return item;
}
else if ((q = p.next) == null) {//无数据
updateHead(h, p);//跟新head,允许失败
return null;
}
else if (p == q)//异常,重新遍历
continue restartFromHead;
else
p = q;//链表遍历,获取下一节点
}
}
}
网友评论