1、1.7版本的底层实现
HashMap在1.7版本中数据结构是数组+链表,
1.1 put方法
put方法中操作步骤:
(1)、对key计算相应的hash值,然后通过hash & table.length-1计算可以获得到在hash表中中相应的桶位置,循环遍历其链表,比较其key值,如果相等,则更新其value的值
(2)如果不相等,则判断是否需要扩容,其中扩容的判断条件是,其size>table.length*0.75.其中0.75是负载因子,如果超过,则扩容。没有超过,则头插入的方式,插入到链表表头。
public V put(K key, V value) {
// 如果key为null,单独处理
if (key == null)
return putForNullKey(value);
int hash = hash(key);//计算出哈希值
int i = indexFor(hash, table.length);//通过哈希值计算出哈希桶的位置
//遍历链表,判断是否有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++; // 更新次数+1
addEntry(hash, key, value, i); // 没有找到相同的
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);//自动扩容,并重新哈希
hash = (null != key) ? hash(key) : 0;
bucketIndex = hash & (table.length-1);//hash%table.length
}
//在冲突链表头部插入新的entry
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
void resize(int newCapacity) {
//这里获取老table的长度,如果老table的长度已经是最大的容量了,那就没必要扩容了,直接返回。
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//如果可以扩容,则new一个新的数组
Entry[] newTable = new Entry[newCapacity];
//transfer方法将老数组的数据copy到新数组当中
transfer(newTable, initHashSeedAsNeeded(newCapacity));
//transfer完了, 就把新数组赋给全局变量table
table = newTable;
//再用新数组的容量计算新的阈值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
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); //重新计算hash值
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;//继续下一个元素
}
}
}
其中扩容的操作是:
(1)创建一个新的hash表,长度为原表的两倍,然后将oldtable的数据拷贝到新表中。那怎么拷贝呢?
(2)因为拷贝到新表,hash值需要重新计算,key的hash和新表的length-1进行计算,然后插入到新表中,如果hash桶存在链表,则使用头插入的方式,插入到新表中。这会导致数据在新表中是倒置的。如下图所示:
(3)将新表赋值给table
头插入法导致的并发问题:
此时头插入方法会导致链表死循环,具体过程是如下:
(1)当并发情况下,假设T1和T2都并发put,并且都符合扩容的条件,对其进行相应扩容,如下图所示,当程序执行到 Entry<K,V> next = e.next; 时候,T2休息,T1继续执行直到扩容结束。
(2)T1结束之后,T2被唤醒,由于是new出来的新对象,对于T2而言也是一个新的数组,然后对A插入到头结点,接着B插入到头节点,然后执行新表中的A,由于table中的B在上述T1中已经指向了A,所以按照resize代码的头插入法,A的next肯定指向新表中的B,此时在新表中陷入了死循环。
1.2 get方法
get方法还是很简单,通过key的hash获取到hash表中的位置,然后遍历其列表,通过比较key,如果相等则返回其entry对象。
final Entry<K,V> getEntry(Object key) {
......
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[hash&(table.length-1)];//得到冲突链表
e != null; e = e.next) {//依次遍历冲突链表中的每个entry
Object k;
//依据equals()方法判断是否相等
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
2、1.8版本的底层实现
1.8版本增加了红黑树,当链表个数大于8个时,会生成红黑树,当相同的hash个数小于6个时,红黑树也会退化成链表
2.1 put方法
(1)计算相应key的hash,然后hash&table.length-1,获取在数组中桶的位置,如果为空则直接new Node插入即可。
(2)如果table[i] != null。则判断此key是否相等,如果相等,则更新老的值
(3)如果table[i]是树节点,将此节点插入到树中
(4)如果table[i]是链表,则遍历链表,如果链表找到,则更新老的值,如果没有找到则使用尾插入插入其节点,插入之后,当节点个数大于8个,则转换成红黑树
(5)插入之后,查看size是否大于阈值,如果符合则resize。
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
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;
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);
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;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
2.2 扩容方法
(1)肯定也会创建一个新表,这是新表直接赋值给了了table,此时会存在一个并发问题,当扩容时,如果此时有一个线程get查询此table数组,则查询不到相应的数据。
(2)遍历oldtable,然后将数据迁移到新表中。遍历桶中如果只有一个节点,则直接通过hash计算到新表中桶的位置,赋值即可
(3)如果此节点是树节点,直接迁移此树到新表中
(4)如果此节点为链表,此时有一个知识点,新表的长度为老表中的2倍,相当于2进制中的高位为1,也就是说链表中hash的二进制高位为1 的放到j+oldCap中,高位为0的则放到j中,并且是顺序放置。
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;
@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;
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
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
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;
}
2.3 get方法
get方法就比1.7多了一步在树中查询
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
总结1.7和1.8的区别:
1、结构不一致,1.7是数组+链表,1.8是数组+链表+红黑树
2、扩容时机,1.7是在扩容之后插入的数据,1.8是插入之后进行扩容
3、插入方式不一样,1.7是头插入方法,使得链表数据在新表中是倒置的,1.8则是尾插入法,使得在新表中的数据是和老表中的插入顺序是一致的
4、并发问题,1.7 头插入方法会导致在并发的时候死循环,1.8解决了此问题,使用尾插入方法,但是在扩容的时候先对table进行赋值,使得并发get的时候,获取到空值。1.7在并发put的时候,如果一个线程在扩容,由于table不具备可见性,所以另一个线程对table进行插入数据后,第一个线程会将新表覆盖老表,而第二个线程在老表插入的数据则会丢失。1.8也解决了此问题,现在HashMap会在扩容时确保所有线程都看到的是最新的数据副本,即使有线程在执行扩容操作。