title: JUC.ConcurrentHashMap与HashMap
提纲
这一章东西比较多分开来写可以写四篇,所以不是一个晚上可以写完。我决定尽快在这两天写完。
这一章的内容推荐可以看看《码出高效》深入浅出,提高思维深入,摸着良心说。
对于代码中涉及到的复杂数据结构不会过多的深入进去写,因为东西太多。后面找个时间单独写数据结构。
为什么要写这一块的东西?
首先比较1.7与1.8代码的差异能学习到优秀的设计思想。
其次Doug Lea大师写的代码我真不信有很多人能打爆他,这么优秀的代码有什么理由不学习?难道对这代码就不感兴趣?就不想看看?
从中可以学到什么?
1.数据结构,算法。如何使用时间复杂度判断一个算法好坏。
2.并发编程
3.对于复杂代码的拆解学习方法(讲真1.8的ConcurrentHashMap真的有点复杂。。。尼玛又不是6000行hello world都是大师的精华代码)
4.甚至其中还有到了内存伪共享的处理。。。细节处理给跪了。
1.7HashMap
1.7中的HashMap是使用的数组加单链表实现。使用链表是为了解决Hash冲突,因为哪怕不同的key的时候也可能造成hashcode一样。
但是用链表查找数据的时间复杂度是O(n),链表越长很可能查询时间越长,因为需要依次遍历下去查找数据。
这也是为什么很多人说链表适合插入修改而数组适合查询的原因。
下面咱们再看一张数据结构图
对于HashMap的数据结构有了认识,咱们可以从源码开始看了主要看put和get。
public V put(K key, V value) {
//1.key为null单独拿出来放
if (key == null)
return putForNullKey(value);
//2.计算key的hash值
int hash = hash(key.hashCode());
//3获取数组下标
int i = indexFor(hash, table.length);
//4.遍历当前下标处的链表是否有同样key的值,有则更新。然后返回旧值
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
//5.没有相同key,添加数据到链表头
addEntry(hash, key, value, i);
return null;
}
上面的源码可以分为如下几个步骤
1.key为null单独拿出来放
2.计算key的hash值
3获取数组下标
4.遍历当前下标处的链表是否有同样key的值,有则更新。然后返回旧值
5.没有相同key,添加数据到链表头
下面咱们继续看源码
计算hash值
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
这段代码不必多说
获取数组下标
static int indexFor(int h, int length) {
return h & (length-1);
}
遍历的代码就在上面不用解释了,主要看下面的添加entry到链表
这里会存在两个步骤
1.容量够了直接添加
2.超了容量扩容
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);//如果超了扩容
}
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);//拷贝数据
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
好了上面就结束了整个1.7 HashMap的put过程。可能存在初始化对象的时候初始化数组这些代码没写,不过这段代码看下构造函数就可以了。
public V get(Object key) {
//1.为null的key特殊处理
if (key == null)
return getForNullKey();
//2.获取hash值
int hash = hash(key.hashCode());
//3.获取数组下标的链表,然后遍历链表。
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
在上面的注释中已经把流程写清楚了。
1.8HashMap
相比较1.7有如下两点的改动
1.1.7使用头部插入链表entity性能更好但是容易死循环,1.8使用链表与红黑树使用尾部插入。
2.1.7扩容每次都重新计算hash,1.8使用1.7计算hash的公式规律可以快速直接算出来。
先上一张1.8的示例图
下面咱们看代码从put开始
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//判断是否为空map,为空初始化。默认16大小
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//判断数组中是否存在,没有添加数据
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
//获取数组下标中的node,供后面替换value用
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//是否红黑树,是走红黑树添加
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//循环遍历链表
for (int binCount = 0; ; ++binCount) {
//添加链表数据
if ((e = p.next) == null) {
//在链表尾部添加
p.next = newNode(hash, key, value, null);
//发现到8个了且tab大于MIN_TREEIFY_CAPACITY的值64,升级为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//红黑树主要升级逻辑,后面另外开一张写红黑树的时候例子中写。
treeifyBin(tab, hash);
break;
}
//发现链表中有一样的中断,后面执行value替换
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//相同key的数据内容替换,onlyIfAbsent这个字段默认是false
if (e != null) {
// existing mapping for key
V oldValue = e.value;
//onlyIfAbsent控制是否替换内容,也许后面会新增一个构造函数。
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//如果是替换value返回旧值
return oldValue;
}
}
++modCount;
//超了阈值,扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
//添加的一律返回一个null
return null;
}
上面的代码主要分为以下三个步骤
1.是否初始化数组大小默认16
2.添加或修改数据
3.是否扩容
下面看一下扩容的代码
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
//扩容阈值大于2的30次方,只能把阈值再调到int最大了。数组将不再会扩容,但是数据还可以存储进去,但是查询性能也会明显下降。哪怕是红黑树。
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;加大扩容阈值
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold扩容一倍数组
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;