基本概念
//默认容量 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//左移4位
//加载因子 0.75f
static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
加载因子0.75的意思是这个表超过75%容量的时候,就会扩容。0.75是一个经过大量实验测算得出的比较好的值,不要问为什么不是0.6或者0.8什么的…
-
HashMap的底层jdk1.8后是“数组+链表+红黑树”,之前是“数组+链表。说白了就是默认长度为16的数组,每个元素存储的是一个链表或者是红黑树的头结点。
-
哈希碰撞指的是key不同,但是计算的hash值相同或者在数组中的索引值相同了。HashMap来解决这个问题就是用了链表。当碰撞很多时,HashMap就退化成了一个链表,查询时间0(n)。在jdk1.8开始呢增加了红黑树(查询时间O(logn))这种数据结构,在碰撞结点较少时,就采用链表,当碰撞结点较多时,就转为红黑树。
-
HashMap是线程不安全的。HashTable是线程安全的,因为添加了synchronized关键字来确保线程同步。
源码分析
- 构造方法
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;
this.threshold = tableSizeFor(initialCapacity);
}
//会根据传入的cap值计算一个数组大小,这个方法得到的一定是一个2的几次方的值
//也就是说数组的长度一定是2的N次方,这么设计主要是为了较少哈希碰撞的产生
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;
}
- hash值的计算
//计算hash值:将hashCode与hashCode的高16位异或运算
//为什么要用高16位来运行,其实也是为了减少哈希碰撞
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//计算在数组中的索引
(n - 1) & hash
- 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;
//数组为空则初始化
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//计算索引,取该索引保存的节点赋值给p
if ((p = tab[i = (n - 1) & hash]) == null)
//该位置没有节点则新建节点放在该位置
tab[i] = newNode(hash, key, value, null);
else {//该位置已经有节点了
Node<K,V> e; K k;
//如果hash值和key都相同
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个,如果超过则调用treeifyBin方法将链表节点转为红黑树节点
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//找到hash值并且key相同的节点
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;
}
- get
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;
}
- 扩容
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) {
//旧表超过最大容量,将阈值改为Integer最大值,结束
threshold = Integer.MAX_VALUE;
return oldTab;
}
//得到新表长度为旧表*2
//如果新表长度在最大最小容量之间,则新阈值为旧阈值*2
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
//旧表长度为0,但是阈值大于0
else if (oldThr > 0)
newCap = oldThr;
else {//旧表长度为0,但是阈值为0
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//新表阈值为0,通过负载因子计算
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)
//该索引位置只有1个节点,则直接放入新表
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
//如果是红黑树节点,则进行红黑树的重hash分布
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { //是链表
//这里定义两个链表节点
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;
}
//该节点在新表的位置发生了变化:旧表的索引位置+oldCap
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;
}
那么我们肯定想知道HashMap是什么时候扩容的?
1.数组空的时候后会扩容
2.当HashMap中元素总个数(不是数组元素个数)达到阈值时就会扩容。
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
3.链表转红黑树的时候,如果数组长度小于64,则会扩容
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
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);
}
}
那么为什么要扩容?
1. HashMap中元素个数实在太多了,已经很频繁的发生hash冲突,
不得不进行扩容来减少这个冲突,来增强效率。
2. 可能元素都集中在某几个位置造成了分布不均匀,数组空间浪费,效率低。
补充ConcurrentHashMap
jdk1.8之后,ConcurrentHashMap的底层也是数组+链表+红黑树。我们知道HashMap是线程不安全的,而HashTable只是简单的在方法上加锁实现线程安全,效率低下,所以在线程安全的环境下我们通常会使用ConcurrentHashMap。这里我们主要想看下为什么ConcurrentHashMap是线程安全的。
- 先看下初始化数组的操作
CAS是乐观锁技术,当多个线程尝试使用CAS同时更新同一个变量时,
只有其中一个线程能更新变量的值,,失败的线程并不会被挂起,
而是被告知这次竞争中失败,并可以再次尝试。
private final Node<K,V>[] initTable() {
Node<K,V>[] tab; int sc;
//如果数组为空,就一直循环试图去初始化
while ((tab = table) == null || tab.length == 0) {
if ((sc = sizeCtl) < 0)//sizeCtl小于0说明有其他线程正在初始化
Thread.yield();//将当前线程挂起,让出CPU时间
//sizeCtl不小于0,说明没有其他线程在初始化数组
//将sizeCtl修改为-1,表示该线程正在初始化数组
else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {
try {
//再次判断数组是否被初始化
if ((tab = table) == null || tab.length == 0) {
//因为sc为0,所以n就是DEFAULT_CAPACITY也就是16
int n = (sc > 0) ? sc : DEFAULT_CAPACITY;
//初始化数组,长度为16
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];
table = tab = nt;
sc = n - (n >>> 2);
}
} finally {
sizeCtl = sc;
}
break;
}
}
return tab;
}
- 计算hash值
static final int spread(int h) {
//将hashCode的高16位和低16位异或运算
//再和0x7fffffff相与运算是为了得到正数
return (h ^ (h >>> 16)) & HASH_BITS;
}
//计算索引
(n - 1) & hash)
- put操作
final V putVal(K key, V value, boolean onlyIfAbsent) {
//不允许key或者value为null
if (key == null || value == null) throw new NullPointerException();
//计算hash值
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0)
tab = initTable();//初始化数组
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {//如果该位置没有节点
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break;
}
//如果正在扩容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {//表示是链表
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
//尾插法
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
//如果红黑树
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
else if (f instanceof ReservationNode)
throw new IllegalStateException("Recursive update");
}
}
if (binCount != 0) {
//链表转红黑树
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
put操作如何保证线程安全的呢?
1.table变量加了volatile保证其引用的可见性,
并不能确保其数组中的对象是否是最新的。
2.将 Node 链表的头节点作为锁
3.使用Unsafe的getObjectVolatile方法取值
- 移除
public V remove(Object key) {
return replaceNode(key, null, null);
}
final V replaceNode(Object key, V value, Object cv) {
int hash = spread(key.hashCode());
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
//数组为空或者没有找到该key对应的元素
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
break;
//正在扩容
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
boolean validated = false;
synchronized (f) {//对f加锁
if (tabAt(tab, i) == f) {
if (fh >= 0) {//链表
validated = true;
for (Node<K,V> e = f, pred = null;;) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
V ev = e.val;
if (cv == null || cv == ev ||
(ev != null && cv.equals(ev))) {
oldVal = ev;
if (value != null)
e.val = value;
else if (pred != null)
//如果移除的是非头结点
pred.next = e.next;
else
//如果是移除的就是头结点
setTabAt(tab, i, e.next);
}
break;
}
pred = e;
if ((e = e.next) == null)
break;
}
}
else if (f instanceof TreeBin) {
validated = true;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) {
V pv = p.val;
if (cv == null || cv == pv ||
(pv != null && cv.equals(pv))) {
oldVal = pv;
if (value != null)
p.val = value;
else if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
else if (f instanceof ReservationNode)
throw new IllegalStateException("Recursive update");
}
}
//调用addCount方法,将当前ConcurrentHashMap存储的键值对数量-1
if (validated) {
if (oldVal != null) {
if (value == null)
addCount(-1L, -1);
return oldVal;
}
break;
}
}
}
return null;
}
5.get方法
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
get操作保证线程间的可见性即可
- 扩容
final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) {
Node<K,V>[] nextTab; int sc;
if (tab != null && (f instanceof ForwardingNode) &&
(nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) {
int rs = resizeStamp(tab.length);
while (nextTab == nextTable && table == tab &&
(sc = sizeCtl) < 0) {
if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||
sc == rs + MAX_RESIZERS || transferIndex <= 0)
break;
if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
transfer(tab, nextTab);
break;
}
}
return nextTab;
}
return table;
}
private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
int n = tab.length, stride;
if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
stride = MIN_TRANSFER_STRIDE; // subdivide range
//如果nextTab为空则初始化为原tab的两倍
if (nextTab == null) { // initiating
try {
@SuppressWarnings("unchecked")
Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
nextTab = nt;
} catch (Throwable ex) { // try to cope with OOME
sizeCtl = Integer.MAX_VALUE;
return;
}
nextTable = nextTab;
transferIndex = n;
}
//假设为16*2=32
int nextn = nextTab.length;
//创建一个标记Node对象,hash值为-1
ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
boolean advance = true;
boolean finishing = false; // to ensure sweep before committing nextTab
for (int i = 0, bound = 0;;) {
Node<K,V> f; int fh;
while (advance) {
int nextIndex, nextBound;
if (--i >= bound || finishing)
advance = false;
else if ((nextIndex = transferIndex) <= 0) {
i = -1;
advance = false;
}
else if (U.compareAndSwapInt
(this, TRANSFERINDEX, nextIndex,
nextBound = (nextIndex > stride ?
nextIndex - stride : 0))) {
bound = nextBound;
i = nextIndex - 1;
advance = false;
}
}
if (i < 0 || i >= n || i + n >= nextn) {
int sc;
if (finishing) {
nextTable = null;
table = nextTab;
sizeCtl = (n << 1) - (n >>> 1);
return;
}
if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
return;
finishing = advance = true;
i = n; // recheck before commit
}
}
//此时i=15,取出Node数组下标为15的那个Node,若为空则直接插入fwd
else if ((f = tabAt(tab, i)) == null)
advance = casTabAt(tab, i, null, fwd);
else if ((fh = f.hash) == MOVED)
advance = true; // already processed
else {//要扩容处理的
synchronized (f) {//对f加锁
if (tabAt(tab, i) == f) {
Node<K,V> ln, hn;
if (fh >= 0) {
//此时fh与原来Node数组长度进行与运算
int runBit = fh & n;
Node<K,V> lastRun = f;
for (Node<K,V> p = f.next; p != null; p = p.next) {
int b = p.hash & n;
if (b != runBit) {
runBit = b;
lastRun = p;
}
}
//低位Node
if (runBit == 0) {
ln = lastRun;
hn = null;
}
//高位Node
else {
hn = lastRun;
ln = null;
}
for (Node<K,V> p = f; p != lastRun; p = p.next) {
int ph = p.hash; K pk = p.key; V pv = p.val;
if ((ph & n) == 0)
ln = new Node<K,V>(ph, pk, pv, ln);
else
hn = new Node<K,V>(ph, pk, pv, hn);
}
//低位的话位置没有变化
setTabAt(nextTab, i, ln);
//高位的话位置发生了变化 i+n
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
else if (f instanceof TreeBin) {
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> lo = null, loTail = null;
TreeNode<K,V> hi = null, hiTail = null;
int lc = 0, hc = 0;
for (Node<K,V> e = t.first; e != null; e = e.next) {
int h = e.hash;
TreeNode<K,V> p = new TreeNode<K,V>
(h, e.key, e.val, null, null);
if ((h & n) == 0) {
if ((p.prev = loTail) == null)
lo = p;
else
loTail.next = p;
loTail = p;
++lc;
}
else {
if ((p.prev = hiTail) == null)
hi = p;
else
hiTail.next = p;
hiTail = p;
++hc;
}
}
ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
(hc != 0) ? new TreeBin<K,V>(lo) : t;
hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
(lc != 0) ? new TreeBin<K,V>(hi) : t;
setTabAt(nextTab, i, ln);
setTabAt(nextTab, i + n, hn);
setTabAt(tab, i, fwd);
advance = true;
}
}
}
}
}
}
1. 扩容时假如有个线程在get操作,而且操作的下标一样呢?
会调用ForwardingNode的find方法,会去新的数组中查找。
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
Node<K,V> find(int h, Object k) {
// loop to avoid arbitrarily deep recursion on forwarding nodes
outer: for (Node<K,V>[] tab = nextTable;;) {
Node<K,V> e; int n;
if (k == null || tab == null || (n = tab.length) == 0 ||
(e = tabAt(tab, (n - 1) & h)) == null)
return null;
for (;;) {
int eh; K ek;
if ((eh = e.hash) == h &&
((ek = e.key) == k || (ek != null && k.equals(ek))))
return e;
if (eh < 0) {
if (e instanceof ForwardingNode) {
tab = ((ForwardingNode<K,V>)e).nextTable;
continue outer;
}
else
return e.find(h, k);
}
if ((e = e.next) == null)
return null;
}
}
}
2.扩容的时候有个线程在put怎么办?
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
3.什么时候会扩容?
put时候如果该位置为ForwardingNode节点会一起扩容;链表转红黑树时数组长度小于64的时候会扩容。