ConcurrentHashMap源码
前言
作为Java集合中线程安全的Map结构,本篇文章主要从源码出发,探究相比HashMap,ConcurrentHashMap是如何保证线程安全的。
一、基础知识
1.Java基础数据类型、字节、位
在源码中出现以下代码:
static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash
1、16进制数以0x开头,每个数字占4bit,8位16进制是4个字节,是一个int整形。
2、F的二进制是:1111。
3、7的二进制是:0111。
4、0x7fffffff的二进制表示为第一位是0,剩下的都是1。
2、transient关键字
该关键字声明的参数在对象序列化的时候不会被序列化,使用该关键字的参数一般可以由其他参数推导出来,或者序列化前后意义弱化,锁表示的值是不需要关注的属性。比如HashMap源码中的modCount参数就使用了该关键字进行标注,主要用于判断HashMap是否被修改。不参与序列化的原因应该主要是为了空间和性能考虑。
二、源码方法
插入元素
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
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;
//ConcurrentHashMap底层存储KV集合数据的结构:Node<K,V>[],与HashMap相同
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表对应位置元素尚未初始化,则CAS自旋初始化
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
//如果当前位置的 hashcode == MOVED == -1,则需要进行扩容。
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
//hash表对应位置已经有元素,则追加
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) {
//容量大于TREEIFY_THRESHOLD则转化成红黑树
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
hash表初始化:
/**
* Initializes table, using the size recorded in sizeCtl.
*/
private final Node<K, V>[] initTable() {
Node<K, V>[] tab;
int sc;
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)
//这里的自旋:如果sizeCtl<0说明有其他线程正在修改,则放弃CPU使用权,为自旋
Thread.yield(); // lost initialization race; just spin
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<K, V>[] nt = new Node<?, ?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
总结
JDK1.8环境下ConcurrentHashMap用了CAS自旋以及synchronized保证线程安全,主要原因时synchronized引入锁升级后性能得到了很大的提升。数据结构与HashMap相同,为Node<K,V>[]+链表/红黑树。