在之前的文章中,已经发布了常见的面试题,这里我花了点时间整理了一下对应的解答,由于个人能力有限,不一定完全到位,如果有解答的不合理的地方还请指点,在此谢过。
本文主要描述的是java多线程中高频面试点concurrentHashMap,concurrentHashMap在实现上和hashMap有很多相似之处。比如底层的数据结构,扩容的倍数,计算table值等等。和hashMap最大的区别就是如何保证线程安全,下面我们也会重点描述其线程安全的保证。如果对hashMap的内容感兴趣,可以看下公众号中之前的文章,有关于hashmap的面试和hashmap的源码解析。如果对java多线程感兴趣的同学可以看下公众号里多线程系列的文章,也许会对你有些帮助。
ConcurrentHashMap的源码有看过,说说其put和get流程?
concurrentHashMap是concurrent包中的重点内容,其put和get过程和hashMap的实现有一定的相似之处,毕竟底层的数据结构是一致的如下。
put过程:
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());//计算hash值,这个hash的计算是为了达到更均匀的分布
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)))
break; // cas添加第一个值
}
else if ((fh = f.hash) == MOVED)//如果正在扩容
tab = helpTransfer(tab, f);//帮助扩容
else {
V oldVal = null;
synchronized (f) {//锁住该hash桶的头节点
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)))) {//hash和equals相等
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&