1.前言
在java编程中,用到的集合容器非常多,hashmap就是其中一种。
2.数据结构
hashmap底层的数据结构在jdk8之前是数组加链表,在jdk8改成了数组、链表、红黑树。
3.死锁
jdk7版本的hashmap在多线程的环境下可能回造成cpu100%的情况,接下来分析下这个场景。
- 分析
先贴一段jdk7的扩容代码
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
大致解释下上面的代码:
首先这是扩容是触发的代码
第二行是获取新的数组的长度
接下来开始遍历扩容前的数组
数组下标里面对应的每个节点都有可能是链表,因此通过while在遍历链表
接下来第五行进来 代表e不为空,把e的下一个节点赋值给临时节点
第六行和第七行是重新计算下hash值