static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 默认初始值
static final int MAXIMUM_CAPACITY = 1 << 30; //最大值
static final float DEFAULT_LOAD_FACTOR = 0.75f; //加载因子
static final int TREEIFY_THRESHOLD = 8; //转化为红黑树的链表的最小长度
static final int MIN_TREEIFY_CAPACITY = 64; //转化为红黑树的数组的最小长度
static final int UNTREEIFY_THRESHOLD = 6; //退化为链表的长度
transient Node[] table; //存放的数组
transient Set> entrySet; //键值对的集合
transient int size; //元素个数
transient int modCount; //并发修改异常
final float loadFactor; //自定义加载因子
hash(key) 返回object的hashCode的值
helpTransfer(Node[] tab, Node f) 如果正在扩容,该线程也加入到扩容中
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[] tab; //存放元素的数组
Node p; //产生hash冲突时的首节点
int n, i; //我们首先可能会想到采用%取余的操作来实现。但是,重点来了:“取余(%)操 作中如果除数是2的幂次则等价于与其除数减一的与(&)操作(也就是说 hash%length==hash&(length-1)的前提是 length 是2的 n 次方;)。” 并且 采用二进制位操作 &,相对 于%能够提高运算效率,这就解释了 HashMap 的长度为什么是2的幂次方
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //1.如果没有初始化就进行初始化
if ((p = tab[i = (n - 1) & hash]) == null) //2.通过hash值计算数组的索引,如果为空,则直接创建节点插入
tab[i] = newNode(hash, key, value, null);
else {
//3.不为空,产生了hash冲突
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p; //4.key相等或key是同一个引用,e记录下来
else if (p instanceof TreeNode) //5.如果当前是红黑树,转化成红黑树节点的插入
e = ((TreeNode)p).putTreeval(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) { //6.如果是链表的话,对链表进行遍历
if ((e = p.next) == null) { //7.到达链表末尾,进行插入,如果链表长度大于等于8时,再在(treeifyBin)里面判断数组长度是否大于等于64,如果时则转化为红黑树,否则直接扩容。(此时e为空了)
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//8.如果存在覆盖,也跳出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//9.e为空就是红黑树的插入,e不为空就是链表的覆盖,覆盖之后size不变,直接返回。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//10,插入新节点之后,modcount自己,防止并发修改异常,判断是否需要扩容,如果是则进行扩容。
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
final Node[] resize() {
Node[] oldTab = table; //保存老数组的值
int oldCap = (oldTab == null) ? 0 : oldTab.length; // 老数组长度
int oldThr = threshold; //老阔容得临界值
int newCap, newThr = 0;//新容量,新临界值
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) { //1.如果数组长度达到Integer的最大值,就不进行扩容了
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && //2。否则就扩到原来的2倍
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; //3.初始化
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//3.重新计算临界值
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"})
//4.将老数组得元素迁移到新数组中
Node[] newTab = (Node[])new Node[newCap];
table = newTab; //将table指向新数组
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) { //5.数组不为空得需要迁移
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e; //6.只有一个元素得链表得迁移
else if (e instanceof TreeNode)
((TreeNode)e).split(this, newTab, j, oldCap); //7.是红黑树时得迁移
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node next;
do {
next = e.next; //8.从链表头开始迁移
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e; // 9.尾插法
}
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) { //索引变为原来得2倍
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
ConcurrentHashMap
//全部用volatile修饰 transient volatile Node[] table; private transient volatile Node [] nextTable; //扩容用的数组 private transient volatile long baseCount; private transient volatile int sizeCtl; private transient volatile int transferIndex; private transient volatile int cellsBusy; private transient volatile CounterCell[] counterCells; static final int NCPU = Runtime.getRuntime().availableProcessors();//扩容时采用多线程扩容 private static final int MIN_TRANSFER_STRIDE = 16;//扩容时的每个转移步骤的最小重新局数,细分范围以允许多个调整器线程。此值用作下限,以避免大小调整器遇到过多内存争用。该值应至少为默认容量。,细分范围 private static final int RESIZE_STAMP_BITS = 16;//时间戳,防止cas多线程扩容时引发的ABA问题 resizeStamp(n);//返回时间戳
//计算索引下标的第一个值 static finalNode tabAt(Node [] tab, int i) { return (Node )U.getReferenceAcquire(tab, ((long)i << ASHIFT) + Abase); } //cas插入节点 static final boolean casTabAt(Node [] tab, int i, Node c, Node v) { return U.compareAndSetReference(tab, ((long)i << ASHIFT) + Abase, c, v); } //cas扩容 static final void setTabAt(Node [] tab, int i, Node v) { U.putReferenceRelease(tab, ((long)i << ASHIFT) + Abase, v); }
put
spread(int h) { //二次哈希
return (h ^ (h >>> 16)) & HASH_BITS;
}
public V put(K key, V value) {
return putVal(key, value, false);
}
final V putVal(K key, V value, boolean onlyIfAbsent) {
//1.键和值都不能为空
if (key == null || value == null) throw new NullPointerException();
//2.二次hash键得hashCode
int hash = spread(key.hashCode());
int binCount = 0;
for (Node[] tab = table;;) {
Node f;
int n, i, fh;
K fk; V fv;
if (tab == null || (n = tab.length) == 0)
tab = initTable(); //3.没有初始化就进行初始化
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { //4.计算索引为空时,cas进行插入
if (casTabAt(tab, i, null, new Node(hash, key, value)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED) //5.如果此时正在扩容,就把节点传过去
tab = helpTransfer(tab, f);
else if (onlyIfAbsent // check first node without acquiring lock//6.如果头节点得引用和key相同,则退出
&& fh == hash
&& ((fk = f.key) == key || (fk != null && key.equals(fk)))
&& (fv = f.val) != null)
return fv;
else {
V oldVal = null;
synchronized (f) { //7.否中使用synchronized进行插入,只锁住头节点,并发度为数组得长度size。
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) { //8.相等则覆盖
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node pred = e;
if ((e = e.next) == null) { //9.否中插入
pred.next = new Node(hash, key, value);
break;
}
}
}
else if (f instanceof TreeBin) { //10.如果是红黑树,则进行红黑树的插入
Node p;
binCount = 2;
if ((p = ((TreeBin)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) { //11.进行了插入判断是否需要扩容
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);//12.判断是否需要扩容
return null;
}
扩容函数
private final void transfer(Node[] tab, Node [] nextTab) { int n = tab.length, stride; //1.计算细分范围 if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) stride = MIN_TRANSFER_STRIDE; // subdivide range if (nextTab == null) { // initiating try { @SuppressWarnings("unchecked") Node [] nt = (Node [])new Node,?>[n << 1]; nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; } nextTable = nextTab; transferIndex = n; } int nextn = nextTab.length; ForwardingNode fwd = new ForwardingNode (nextTab); boolean advance = true; boolean finishing = false; // to ensure sweep before committing nextTab for (int i = 0, bound = 0;;) { //2.从第一个桶开始扩容 Node 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.compareAndSetInt (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) { //扩容完成table指向新的数组 nextTable = null; table = nextTab; sizeCtl = (n << 1) - (n >>> 1); return; } if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) return; finishing = advance = true; i = n; // recheck before commit } } else if ((f = tabAt(tab, i)) == null) //只有一个元素的桶,cas直接插入 advance = casTabAt(tab, i, null, fwd); else if ((fh = f.hash) == MOVED) advance = true; // already processed else { synchronized (f) { //获取第i个桶,cas插入新的table中 if (tabAt(tab, i) == f) { Node ln, hn; if (fh >= 0) { int runBit = fh & n; Node lastRun = f; for (Node p = f.next; p != null; p = p.next) { int b = p.hash & n; if (b != runBit) { runBit = b; lastRun = p; } } if (runBit == 0) { ln = lastRun; hn = null; } else { hn = lastRun; ln = null; } for (Node 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 (ph, pk, pv, ln); else hn = new Node (ph, pk, pv, hn); } setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } else if (f instanceof TreeBin) { TreeBin t = (TreeBin )f; TreeNode lo = null, loTail = null; TreeNode hi = null, hiTail = null; int lc = 0, hc = 0; for (Node e = t.first; e != null; e = e.next) { int h = e.hash; TreeNode p = new TreeNode (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 (lo) : t; hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin (hi) : t; setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } else if (f instanceof ReservationNode) throw new IllegalStateException("Recursive update"); } } } } }



