ConcurrentHashMap 在功能上与 HashTable 一致,都是线程安全的键值对容器。但是 ConcurrentHashMap 比 HashTable 有更好的并发性能:
1. HashTable 是同步的,也就是说,它的所有方法都是被 synchronized 修饰的。所以当 thread-1 进入 put 方法时,其它所有线程都不能进入 put/get 方法。这样做可以确保线程安全,但是在高并发的场景下,效率比较低。HashTable 的代码片段如下:
public synchronized V put(K key, V value) {
...
}
public synchronized V get(Object key) {
...
}
2. ConcurrentHashMap 对读操作不加锁,对写操作部分加锁,所以支持较高的并发。
这是 ConcurrentHashMap 的 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;
}
static final int spread(int h) {
return (h ^ (h >>> 16)) & HASH_BITS;
}
static final int MOVED = -1; // hash for forwarding nodes
static final int TREEBIN = -2; // hash for roots of trees
static final int RESERVED = -3; // hash for transient reservations
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
static class Node<K,V> implements Map.Entry<K,V> {
...
/**
* Virtualized support for map.get(); overridden in subclasses.
*/
Node<K,V> find(int h, Object k) {
Node<K,V> 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;
}
}
可以看出以下几点:
1. get 函数不是同步方法,没有加锁。
2. ConcurrentHaspMap 里面的节点有好几种类型,可以通过 table 里元素的key 来判断属于那一种。
2.1. Node:继承自 Map.Entry,除了 hash / key / val 之外,还有一个 next 字段。所以使用单向链表来解决 hash 冲突的。
2.2. ForwardingNode:是一个标记节点,本身不保存数据,hash 值固定为 MOVED(-1)。当 ConcurrentHaspMap 扩容时会用到这个节点。ForwardingNode 的 nextTable 字段保存了 扩容后的新节点,所以需要查找节点,就到 nextTable 中去查找。
2.3. ReservationNode:只是一个占位符,它用在 computeIfPresent 或者 compute 这样的函数中。它的 find 函数直接返回 null。
2.4. TreeBin:当 table 中的某个桶为数时,桶里就放 TreeBin。TreeBin 本身并不保存数据,数据是保存在 TreeNode 里面的。TreeNode 保存 TreeNode 节点以及它们的根节点。TreeBin 持有读写锁,强迫写线程(持有锁)必须在读线程(不持有锁)读取完成之后,再进行树的重构。(红黑树左旋、右旋)。
2.5. TreeNode:TreeBin 中使用的数据节点。
这是 ConcurrentHashMap 的 put 方法:
public V put(K key, V value) {
return putVal(key, value, false);
}
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;
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, 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) { // 只对 table 中的某一项加锁。
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)))) { // 找到相同 key 的Entry
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) { // key 不存在
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) // bin 中访问过的节点数 >= 8 由链表转换成红黑树。
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
参考:
1. https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html