JDK8的源码是Node数组+Node链表+TreeNode组成
常量解释
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 //Node数组默认长度
static final int MAXIMUM_CAPACITY = 1 << 30; //Node数组最大长度
static final float DEFAULT_LOAD_FACTOR = 0.75f; //扩容因子
static final int TREEIFY_THRESHOLD = 8; //有一个Node链表长度大于8 则有可能转化为TreeNode
static final int UNTREEIFY_THRESHOLD = 6; //在Hash表扩容时候,如果发现当前链表长度小于6了则重新退化为Node链表
//在转为TreeNode之前还会有一次会比较Node数组的长度,如果<64则Hash表仅是扩容,这样做的目的是,如果多个K/V恰好在同一个Node链表上导致的不必要的转换
static final int MIN_TREEIFY_CAPACITY = 64;
transient int size;//Hash表中的K-V数量
transient int modCount;//记录Hash表修改的次数,增 删 改 都会+1
int threshold;//可以理解为下一次扩容的阀值
final float loadFactor; //Hash表的实际扩容因子,默认值(0.75)或者自己定义
初始化
HashMap有三个初始化方法
//默认长度16,扩容因子0.75
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
//手动设置容量,默认0.75的扩容因子
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
//手动设置容量<0抛出异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//手动设置容量超过最大容量,为最大容量
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//扩展因子<=0 或者 不合法 抛出异常
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//计算Hash表的扩容阀值
this.threshold = tableSizeFor(initialCapacity);
}
/**
* Returns a power of two size for the given target capacity.
* 翻译:返回大于输入参数且最近的2的整数次幂的数,例如9 返回16 ,17返回32 18返回32
*/
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
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) {
//tab是Hash表的容量数组,p是当前key的计算后的索引值对应的Node节点,n是容器数组的长度,i是key值计算后的索引值
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//如果tab为空,或者n==0 则执行首次扩容
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//当前key值计算后的索引值对应的Node为空,说明当前位置是首次添加
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果当前key与查出来的Node的key hash值相同则直接覆盖老值
e = p;
else if (p instanceof TreeNode)
//当前节点是树类型,树形结构添加节点
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//如果当前Node的next为空,则直接将put的值放在当前Node的next位置,并且要判断是否需要转为TreeNode
//如果当前Node的next不为空就需要循环next一直找到next为空的位置。说明了HashMap的put操作的时间复杂度最好为O(1),最坏O(n)
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//修改次数+1
++modCount;
//如果当前的K-V数量 > 阀值 执行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
Node链表转为Tree
treeifyBin (Node转为TreeNode)
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//容量数组为空或者容量数组长度 < 64 继续扩容,避免不必要的转换
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
扩容
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) {
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;
else { // zero initial threshold signifies using defaults
//首次初始化,容量是默认值,扩容阀值是容量*扩容因子
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//设置扩容阀值
threshold = newThr;
//new一个长度为newCap的Node数组
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//将老的Node数组里的Node重新放到扩容之后的Node数组,分为3中情况,当前Node next为空,TreeNode节点,当前Node next不为空
if ((e = oldTab[j]) != null) {
oldTab[j] = null; //释放老数组的引用
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
//loHead用户存储低位(位置不变)key的链头,loTail用于指向链位位置。
Node<K,V> loHead = null, loTail = null;
//hiHead用户存储即将存储在高位的key的链头,hiTail用于指向链尾位置。
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
//与原数组长度相与后,得到的结果为0的,意味着在新数组中的位置是不变的,因此,将其组成一个链条
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
//对于非0的key,其在新数组中的位置是需要更新的,需要存储在新增的数组中的一个新的位置,将其形成一个链条。
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
扩容避免1.7的出现的环形队列
JDK1.7高并发中出现环形队列的代码
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;
}
}
}
1.8解决这个问题
1、首先改头插法为尾插法
2、使用高位和低位Node节点来放不同位置的Node
线程不安全
putVal()
if ((p = tab[i = (n - 1) & hash]) == null)
//高并发情况下,如果A线程执行完 if 语句,恰好CPU将资源给了B线程,这时候B也走到newNode这一行,那么就会覆盖线程A的值
tab[i] = newNode(hash, key, value, null);
resize()
if (e.next == null)
//这里并没有判断当前索引位置是否存在节点,高并发情况下,假如put和resize同时进行,put的位置恰好是这个索引位置,那么oldNode就会覆盖这个新put的值
newTab[e.hash & (newCap - 1)] = e;