分段锁
jdk 1.8前,采用分段锁。
首先将数据分成一段一段的存储,然后给每一段数据配一把锁,当一个线程占用锁访问其中一个段数据的时候,其他段的数据也能被其他线程访问。
CAS算法
在jdk 1.8,使用CAS算法。
节点上哈希字段的编码
/*
* Encodings for Node hash fields. See above for explanation.
*/
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
原子操作
ConcurrentHashMap定义了三个原子操作,tabAt,casTabAt和setTabAt。
tabAt():获得在i位置上的Node节点
@SuppressWarnings("unchecked")
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
casTabAt():利用CAS算法设置i位置上的Node节点。
在CAS算法中,比较内存中的值与当前线程的值是否相等,如果相等才接受修改,否则拒绝修改。因为当前线程中的值可能并不是最新的值,这种修改可能会覆盖掉其他线程的修改结果。
@SuppressWarnings("unchecked")
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
setTabAt():设置节点位置的值
@SuppressWarnings("unchecked")
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
put操作
步骤如下:
- 若数组table未初始化,则使用initTable()初始化node数组
- 使用&运算计算数组下标i,得到tab[i]的f对象f
- 若f为null,则使用CAS算法添加新节点(casTabAt()函数)
- 若f.hash与MOVED相等,表示拓展状态,使用helpTransfer()协助扩容
- 若f是链表节点,则遍历链表,若存在hash与key相等的节点,则覆盖value,否则插入末尾
- 若f是红黑树节点,则插入树中
- 如果节点数大于临界值,链表转换成红黑树
/** 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;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
//第一次添加,先初始化node数组
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)))
//如果table[i]为null,则添加新建的node节点,跳出循环,
//反之,再循环进入执行添加操作
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
//如果f.hash等于当前处于拓展状态,返回拓展后的tab
//f:table[i]的node对象
tab = helpTransfer(tab, f);//进行协助扩容
else {
// 链表中或红黑树中追加节点
// 使用synchronized 对 f 对象加锁,
// f = tabAt(tab, i = (n - 1) & hash) :table[i] 的node对象,
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
//如果是链表节点,则链表上追加节点
if (fh >= 0) {
binCount = 1;
//遍历链表所有的结点
for (Node<K,V> e = f;; ++binCount) {
K ek;
// 如果hash值和key值相同,则修改对应结点的value值
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;
}
}
}
addCount(1L, binCount);
return null;
}
Node
ConcurrentHashMap核心内部类,它包装了key-value键值对,所有插入ConcurrentHashMap的数据都包装在这里面。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
volatile V val;//带有同步锁的value
volatile Node<K,V> next;//带有同步锁的next指针
Node(int hash, K key, V val, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.val = val;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return val; }
public final int hashCode() { return key.hashCode() ^ val.hashCode(); }
public final String toString(){ return key + "=" + val; }
//不允许直接改变value的值
public final V setValue(V value) {
throw new UnsupportedOperationException();
}
public final boolean equals(Object o) {
Object k, v, u; Map.Entry<?,?> e;
return ((o instanceof Map.Entry) &&
(k = (e = (Map.Entry<?,?>)o).getKey()) != null &&
(v = e.getValue()) != null &&
(k == key || k.equals(key)) &&
(v == (u = val) || v.equals(u)));
}
/**
* 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;
}
}
这个Node内部类与HashMap中定义的Node类很相似,但是有一些差别
它对value和next属性设置了volatile同步锁
它不允许调用setValue方法直接改变Node的value域
它增加了find方法辅助map.get()方法