在csdn看了不少HashMap的源码解析,大部分都是基于jdk1.6的。
为了练习,基于自己使用的java10,进行一次HashMap的源码解析。
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
可以看到HashMap继承了AbstractMap类,实现了Map、Cloneable、Serializable三个接口。
开头定义了一些默认常量。
/**
* 该变量定义了HashMap的最大容量。这里定义为2^30。
* 如果构造器传入的容量大于最大容量,使用最大容量代替传入的容量。
* 该值必须为2的n次方。
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 该变量为默认的负载因子,如果没有显式传入负载因子,那么就会使用0.75。
* 负载因子用来确定触发rehash的阈值。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 在Java1.6中,每个桶中都是一条entry的单链表。
* 为了提高查询的效率,该变量表示当entry链表超过某个阈值时,将单链表转化为红黑树。
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 设定将红黑树转化为单链表的阈值。
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 为树设定最小容量。
* 为确保不与TREEIFY_THRESHOLD发生冲突,必须大于等于4 * TREEIFY_THRESHOLD。
*/
static final int MIN_TREEIFY_CAPACITY = 64;
在之前的版本中,使用Entry,现在使用Node,但实质没有改变,是Map中的键值对。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
// 构造器,需要传入hash值,并指定下一个node。
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
接下来看看HashMap中的变量。
/**
* HashMap的实际存储方式,是Node数组。
* 数组的长度必须是2的幂次方。
*/
transient Node<K,V>[] table;
/**
* 用于存储entrySet(),用于keySet()和values()。
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* 用于存储HashMap中键值对的数量。
*/
transient int size;
/**
* 用于记录对HashMap进行结构性改变的次数。
* 结构性改变指增加、删除、再分布操作,不包括对现有的key重新赋值。
* 以便在使用迭代器遍历时,发现产生结构修改后,快速失败重新开始。
*/
transient int modCount;
/**
* 存储目前触发再分布的阈值。
*/
int threshold;
/**
* 用于存储目前的负载因子。
*/
final float loadFactor;
HashMap拥有四种构造函数。
HashMap(int initialCapacity, float loadFactor),HashMap(int initialCapacity),HashMap(),HashMap(Map<? extends K, ? extends V> m) 。前三种都类似,如果不指定初始容量和负载因子,就用前面定义的默认初始常量代替。最后一种传入其他Map类来生成一个HashMap,即里面键值对不变,只是换成了HashMap存储结构。
详细看下第一种和第四种。
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
// 如果初始化容量大于最大容量,则使用最大容量初始化
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 调用tableSizeFor()方法来确保传入的初始化容量为2的幂次方
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
// 使用putMapEntries()方法,将Map对象中的键值对放入HashMap中
putMapEntries(m, false);
}
第四种构造函数调用了putMapEntries()方法,我们来看一下如何批量放入键值对。
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // 如果entry数组尚未初始化,则初始化数组
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold) // 如果要放入的键值对数量大于阈值,则重分布
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
// 调用putVal方法放入键值对
putVal(hash(key), key, value, false, evict);
}
}
}
该方法中,使用遍历传入的Map,放入所有的键值对,具体的方法调用了putVal()。其实,我们使用的put(K key, V value)方法的具体实现也是使用了内部的putVal()方法。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
来看一下putVal()是如何实现的。
/**
* 前面三个参数好理解,就是传入键的hash值,键,值。
* onlyIfAbsent参数若为true,则只当键不存在时,才插入。否则不修改value。
* evict参数若为false,表示在创建模式。
*/
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;
// 如果数组中的bin为空,则新建一个node,存入数组
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) // bin是树结构
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else { // bin是单链表结构
for (int binCount = 0; ; ++binCount) { // 将新node加到链尾
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) { // 如果已存在相同的键,根据onlyIfAbsent决定是否替换值
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 记录结构性修改
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
在前面代码中,若当前的键值对数量大于阈值,则触发重分布,实际是调用resize()方法实现。那么来看一下resize()方法。
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 { // 根据高低位不同,分布到新的bin中
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;
}
这里会有一点疑问,如果bin不是树结构,loHead,loTail,hiHead,hiTail代表什么。简单来说,原来的键值对为什么会分布在同一个bin中,是因为它们key的hash值与容量的值取与后相同。比如123456与120456取后三位都是456,那么它们就存储在同一个bin中。现在重分布后,容量扩大了一倍,在十进制中就表示这两个键值对将分别存储在3456和0456的位置。确切的在二进制中,就表现为存储的位置最低位为0或者1的差别了。这里插入node使用了头插法。
看完增加操作,再来看一下查找操作。查找操作有两种get()和containsKey()。在实现中,这两个方法都委托给内部方法getNode()实现。
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) { // 确保数组不为空,bin不为空
if (first.hash == hash && // 比较bin中的第一个元素
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode) // 若bin是树结构,委托给getTreeNode方法
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;
}
删除操作有两种,一种是删除特定元素
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
查看代码可以发现,是委托给内部方法removeNode()实现的。
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
// 首先查找键值对,方法与查找的方法基本相同
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 查找成功后,对于链表,进行断链,对于树结构,进行移除
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
对于HashMap的遍历,可以通过keySet(),valueSet(),entrySet()获得set后,使用迭代器进行遍历。这里我们主要来看一下entrySet()的迭代器的实现。
final class EntryIterator extends HashIterator
implements Iterator<Map.Entry<K,V>> {
public final Map.Entry<K,V> next() { return nextNode(); }
}
EntryIterator继承自HashIterator,实现了Iterator。其中hasNext()直接使用HashIterator的hasNext()方法,next()委托给HashIterator的nextNode()方法实现。
abstract class HashIterator {
Node<K,V> next; // next entry to return
Node<K,V> current; // current entry
int expectedModCount; // for fast-fail
int index; // current slot
HashIterator() {
expectedModCount = modCount;
Node<K,V>[] t = table;
current = next = null;
index = 0;
if (t != null && size > 0) { // advance to first entry
do {} while (index < t.length && (next = t[index++]) == null);
}
}
public final boolean hasNext() {
return next != null;
}
final Node<K,V> nextNode() {
Node<K,V>[] t;
Node<K,V> e = next;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
if (e == null)
throw new NoSuchElementException();
// 当前bin遍历完毕,但是数组尚未遍历完毕,从下一个bin的头节点继续遍历
if ((next = (current = e).next) == null && (t = table) != null) {
do {} while (index < t.length && (next = t[index++]) == null);
}
return e;
}
public final void remove() {
Node<K,V> p = current;
if (p == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
current = null;
removeNode(p.hash, p.key, null, false, false);
expectedModCount = modCount;
}
}
抛开关于红黑树的内容,HashMap类的大致源码都解读了一下。下一次应该要读一读关于ConcurrentHashMap的源码实现了。最后记一下,为什么HashMap是线程不安全的。
因为在resize()的过程中,HashMap可能产生死循环。resize()时,新建数组,采用头插法将原有的键值对插入其中。
例如两个线程0号和1号,在修改同一HashMap。该HashMap有两个bucket,1号bucket中有4个entry。
现在要将该HashMap rehash到4个bucket中。0号线程获得0号entry,0号entry的next指向1号entry,并被挂起。1号进程开始rehash,如果形成1号entry的next指向0号entry,这是0号进程获得资源继续执行,则0号entry指向1号entry,1号entry指向0号entry,陷入死循环。