前言
本文只介绍put和get操作如何保证线程安全,不介绍多线程扩容等知识。
put操作保证线程安全
先来看一下ConcurrentHashMap的数组的字段定义,有volatile关键字
transient volatile Node<K,V>[] table;
可以看到数组使用volatile表示的,volatile的可见性在此不再赘述,但是这只能保证数组在不同线程之间是可见的,并不能保证数组内的元素在各线程之间是可见的,也就是说table[i]获取下标元素不能保证可见性,那ConcurrentHashMap是怎么实现的呢?我们来看下源码 精简主干代码之后
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh; K fk; V fv;
if (tab == null || (n = tab.length) == 0)
tab = initTable();
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value)))
break;
}
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;
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);
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;
}
}
else if (f instanceof ReservationNode)
throw new IllegalStateException("Recursive update");
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectAcquire(tab, ((long)i << ASHIFT) + ABASE);
}
总结,通过tabAt(tab, i)的cas操作获取数组i下标的元素值。如果为null,则cas赋值,失败则自旋。如果不为null则synchronize锁住当前链表赋值。
get操作保证线程安全
我们先来看一下ConcurrentHashMap的基本元素节点Node的结构,值val和链表下个节点next都用了volatile修饰
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;
volatile Node<K,V> next;
Node(int hash, K key, V val) {
this.hash = hash;
this.key = key;
this.val = val;
}
Node(int hash, K key, V val, Node<K,V> next) {
this(hash, key, val);
this.next = next;
}
...
}
再来看一下get的源码
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
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;
}
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;
}
代码比较简单,总结就是: get操作全程不需要加锁是因为两点(1)获取数组下标对应的值用的cas操作e = tabAt(tab, (n - 1) & h)(2)Node的成员val、next是用volatile修饰的和数组用volatile修饰没有关系。val用在已存在该key,别的线程put操作替换旧址可见,next用在别的线程put操作新增节点可见。
|