ConcurrentHashMap源码理解

时间:2021-07-21 23:45:08

1.ConcurrentHashMap继承关系

ConcurrentHashMap源码理解

ConcurrentHashMap继承了AbstractMap类,同时实现了ConcurrentMap接口。

2.ConcurrentHashMap构造函数

    public ConcurrentHashMap() {
} public ConcurrentHashMap(int initialCapacity) {
if (initialCapacity < )
throw new IllegalArgumentException();
int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> )) ?
MAXIMUM_CAPACITY :
tableSizeFor(initialCapacity + (initialCapacity >>> ) + ));
this.sizeCtl = cap;
} public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
this.sizeCtl = DEFAULT_CAPACITY;
putAll(m);
} public ConcurrentHashMap(int initialCapacity, float loadFactor) {
this(initialCapacity, loadFactor, );
} public ConcurrentHashMap(int initialCapacity,
float loadFactor, int concurrencyLevel) {
if (!(loadFactor > 0.0f) || initialCapacity < || concurrencyLevel <= )
throw new IllegalArgumentException();
if (initialCapacity < concurrencyLevel) // Use at least as many bins
initialCapacity = concurrencyLevel; // as estimated threads
long size = (long)(1.0 + (long)initialCapacity / loadFactor);
int cap = (size >= (long)MAXIMUM_CAPACITY) ?
MAXIMUM_CAPACITY : tableSizeFor((int)size);
this.sizeCtl = cap;
}
ConcurrentHashMap():这个没什么好说的,无参构造函数一切都是使用默认值。
ConcurrentHashMap(int):int指定了实例可以承载的数据容量,如果容量大于允许最大容量的一半,直接初始化为最大容量。否则的话,会先计算数组长度(为容量的1.5倍加1),然后再同hashmap一样,计算大于数组长度的最小的2的幂次方作为数组长度。
ConcurrentHashMap(int,float):内部实际调用了ConcurrentHashMap(int,float,int),最后一个参数填1。
ConcurrentHashMap(int,float,int):参数依次指定了实例可以承载的数据容量initialCapacity,负载因子loadFactor,同步等级concurrencyLevel。初始容量不能小于同步等级,如果小于,则令其等于同步等级的数值。然后用初始容量除以负载因子,获取数组大小,再求出最小的2的幂次方。
ConcurrentHashMap(Map):参数使用默认的参数,同时调用putAll(Map)方法。

3.ConcurrentHashMap添加元素

3.1添加元素核心类

    final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = ;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == )
tab = initTable();
else if ((f = tabAt(tab, i = (n - ) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
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 >= ) {
binCount = ;
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 = ;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != ) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
} private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == ) {
if ((sc = sizeCtl) < )
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -)) {
try {
if ((tab = table) == null || tab.length == ) {
int n = (sc > ) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> );
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}

源码解析:

  1.在concurrentHashMap中要求key和value都不能为空,否则会抛出NPE。

if (key == null || value == null) throw new NullPointerException();

  2.计算key新的hash值

int hash = spread(key.hashCode());
    static final int spread(int h) {
return (h ^ (h >>> )) & HASH_BITS;
}

  3.循环实例中存放元素的table,如果table没有初始化,则进行初始化

        for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == )
tab = initTable();

  首先注意这里的for,它的里面是一个无限循环,也就是说会一直循环下去,直到遇见break。

  初始化table,这里使用了乐观锁U.compareAndSwapInt()方法,有且只有一个线程t能够将SIZECTL设置为-1,此时其他的所有线程都会进入Thread.yield()让出cpu进行循环等待。当t线程执行完最后一行后,对sizeCtl进行了赋值,此时其他的线程会判断tab!=null,且tab.length!=0,因此也会跳出循环,返回已经被t线程创建好的table。

  线程t通过乐观锁,执行初始化table的逻辑,如果实例没有被赋予初始化容量,则使用默认的初始化容量16来作为数组长度创建数组。然后执行sc=n-(n>>>2),实际令sc=0.75sc,求出了在默认0.75f的负载因子下可存储数据数量。最后返回创建的数组node[16]。

    private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
while ((tab = table) == null || tab.length == ) {
if ((sc = sizeCtl) < )
Thread.yield(); // lost initialization race; just spin
else if (U.compareAndSwapInt(this, SIZECTL, sc, -)) {
try {
if ((tab = table) == null || tab.length == ) {
int n = (sc > ) ? sc : DEFAULT_CAPACITY;
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> );
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}

  4.利用tabAt()方法获取数组上对应hash值位置上的值,如果为空,则调用casTabAt方法将新待添加的元素放置在该位置上。

而在tabAt()方法内部,是调用了getObjectVolatile(Node[], int),直接从内存中读取数组中元素的准确值。

同时在casTabAt(Node[], int, Node, Node)中,利用乐观锁进行对空赋值。

        else if ((f = tabAt(tab, i = (n - ) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
} 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);
} 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);
}

  5.如果数组位置上已有值,判断这个值的hash值是否等于-1,等于则调用helpTransfer(node[],int)方法。

            else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);

  6.以上条件都判断后,确定数组元素的正常,通过synchronized获取锁,拿到锁之后,首先判断元素是否已经被其他线程改变了,如果改变了,重新执行for循环,获取新的元素,没有改变则判断元素是链表(hash值大于0)还是红黑树(instanceof TreeBin)。

  (1)链表:从首节点开始遍历,如果找到有相等的key(hash值相等,key也相等),则进行value值的替换,否则创建一个新的节点,添加在链表最后位置。

  (2)红黑树:putTreeVal(int, K, V);

  对元素处理完成后,释放锁,判断当前链表上添加的元素是否大于等于8,如果是,则将当前结构转为树结构。如果是替换了已有的节点,则返回旧值,执行到此结束。

           else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= ) {
binCount = ;
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 = ;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != ) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}

  7.如果是新添加的节点,需要执行最后一步。addCount(long,int)方法

    private final void addCount(long x, int check) {
CounterCell[] as; long b, s;
if ((as = counterCells) != null ||
!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {
CounterCell a; long v; int m;
boolean uncontended = true;
if (as == null || (m = as.length - ) < ||
(a = as[ThreadLocalRandom.getProbe() & m]) == null ||
!(uncontended =
U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {
fullAddCount(x, uncontended);
return;
}
if (check <= )
return;
s = sumCount();
}
if (check >= ) {
Node<K,V>[] tab, nt; int n, sc;
while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&
(n = tab.length) < MAXIMUM_CAPACITY) {
int rs = resizeStamp(n);
if (sc < ) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + ||
sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||
transferIndex <= )
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + ))
transfer(tab, nt);
}
else if (U.compareAndSwapInt(this, SIZECTL, sc,
(rs << RESIZE_STAMP_SHIFT) + ))
transfer(tab, null);
s = sumCount();
}
}
}

_