一 特性
- 在jdk7之中是使用分段锁来保证的(ReentrantLock + Segment + HashEntry) 将HashMap分成多个片段segment,每个段分配一把锁,在8之中使用CAS+Snchronized+Node+红黑树保证的,锁的粒度是Node 首节点
- jdk1.7的结构
- jdk1.8的结构
-
二 属性
```java private static final int MAXIMUM_CAPACITY = 1 << 30;
/* 默认大小 / private static final int DEFAULT_CAPACITY = 16;
// 最大数组长度-转数组使用 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/** 最多的并行度*/private static final int DEFAULT_CONCURRENCY_LEVEL = 16;/**负载因子*/private static final float LOAD_FACTOR = 0.75f;/** 元素超过这个值会转换为红黑树*/static final int TREEIFY_THRESHOLD = 8;/** 总元素最小的转换成树的条件 不满足这个只会扩容*/static final int MIN_TREEIFY_CAPACITY = 64;
// 扩容操作中,单个线程的最小步进 // 数据迁移通过分段迁移,由多线程协调执行,最小段数量为16,则如果长度为16,由一个线程进行扩容 private static final int MIN_TRANSFER_STRIDE = 16;
// 扩容操作使用private static int RESIZE_STAMP_BITS = 16;//最大扩容线程数量
private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1;
// 扩容操作使用,进行sizeCtl高低位移动,进行扩容线程数判断private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS;
/* 实际存储的数组
/
transient volatile Node
/*** 扩容的时候使用的下一个数组*/private transient volatile Node<K,V>[] nextTable;/** 统计数量* races. Updated via CAS.*/private transient volatile long baseCount;// 用于和负数hash值进行 & 运算,将其转化为正数(绝对值不相等)static final int HASH_BITS = 0x7fffffff;
// ForwardingNode的hash值,ForwardingNode是一种临时节点,在扩进行中才会出现,并且它不存储实际的数据,ForwardingNode继承自Node,默认hash初始化为-1 static final int MOVED = -1;
// 红黑树的HASH值 static final int TREEBIN = -2;
// ReservationNode的hash值,ReservationNode是一个保留节点,就是个占位符 static final int RESERVED = -3;
/*
- 非常重要的一个属性,源码中的英文翻译,直译过来是下面的四行文字的意思
- sizeCtl = -1,表示有线程正在进行真正的初始化操作
- sizeCtl = -(1 + nThreads),表示有nThreads个线程正在进行扩容操作
- sizeCtl > 0,表示接下来的真正的初始化操作中使用的容量,或者初始化/扩容完成后的阈值
sizeCtl = 0,默认值,此时在真正的初始化操作中使用默认容量 */ private transient volatile int sizeCtl;
// 扩容任务的起始下标 private transient volatile int transferIndex;
// CAS自旋锁标志位,用于初始化,或者counterCells扩容时使用 private transient volatile int cellsBusy;
// 分段计数,记录 private transient volatile CounterCell[] counterCells;
<a name="W7P87"></a># 三 重要方法- tabAt(Node<K,V>[] tab, int i)- 获取i索引处对象- casTabAt(Node<K,V>[] tab, int i,Node<K,V> c, Node<K,V> v)- 把索引 i 处为C 的对象换成V cas方式比较更新- setTabAt(Node<K,V>[] tab, int i, Node<K,V> v)- 把 i 索引处对象设置为V- tableSizeFor- 给一个传入的数,返回大于给定数字的最小的2的整数次方的数字<a name="S9VT1"></a># 四 添加```javafinal V putVal(K key, V value, boolean onlyIfAbsent) {if (key == null || value == null) throw new NullPointerException();//将hash值进行扰乱 (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16) 这个是hashMap的// (h ^ (h >>> 16)) & HASH_BITSint 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();//unSafe直接读取内存 如果指定位置是null 则直接插入else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {if (casTabAt(tab, i, null,new Node<K,V>(hash, key, value, null)))break; // no lock when adding to empty bin}//扩容阶段else if ((fh = f.hash) == MOVED)tab = helpTransfer(tab, f);else {V oldVal = null;//锁住发生hash冲突的第一个节点synchronized (f) {//加锁之后再重新检查下 避免其他线程对f进行了更改if (tabAt(tab, i) == f) {// 判断头结点的hash值if (fh >= 0) {binCount = 1;//循环链表操作 这里binCount是下边使用进行树化使用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;}}}}if (binCount != 0) {if (binCount >= TREEIFY_THRESHOLD)treeifyBin(tab, i);if (oldVal != null)return oldVal;break;}}}addCount(1L, binCount);return null;}// 初始化数组private final Node<K,V>[] initTable() {Node<K,V>[] tab; int sc;while ((tab = table) == null || tab.length == 0) {if ((sc = sizeCtl) < 0)Thread.yield(); // lost initialization race; just spin//java的cas更新方法 读取传入对象在内存中偏移量为SIZECTL 的值与 sc作比较,相等则将-1赋值进入 表示正在初始化 不相等则返回false// SIZECTL 这个是静态实例已经被初始化为 U.objectFieldOffset(k.getDeclaredField("sizeCtl"));else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) {try {if ((tab = table) == null || tab.length == 0) {int n = (sc > 0) ? sc : DEFAULT_CAPACITY;@SuppressWarnings("unchecked")Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n];table = tab = nt;// 16 - 4=12sc = n - (n >>> 2);}} finally {sizeCtl = sc;}break;}}return tab;}//作用是找到指定位置i的值 使用的是UnSafe直接操作的内存 找到对应位置的偏移量static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);}//cas的方式更新进去 先比较在更新static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,Node<K,V> c, Node<K,V> v) {return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);}//当发生hash冲突 check传入的是链的大小private final void addCount(long x, int check) {CounterCell[] as; long b, s;if ((as = counterCells) != null ||//注意这里会把值累加到 baseCount上 也就是当发生并行访问冲突的时候才会用到下边的代码!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {CounterCell a; long v; int m;boolean uncontended = true;if (as == null || (m = as.length - 1) < 0 ||(a = as[ThreadLocalRandom.getProbe() & m]) == null ||!(uncontended =U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {fullAddCount(x, uncontended);return;}if (check <= 1)return;s = sumCount();}if (check >= 0) {Node<K,V>[] tab, nt; int n, sc;while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&(n = tab.length) < MAXIMUM_CAPACITY) {int rs = resizeStamp(n);if (sc < 0) {if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||transferIndex <= 0)break;if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))transfer(tab, nt);}else if (U.compareAndSwapInt(this, SIZECTL, sc,(rs << RESIZE_STAMP_SHIFT) + 2))transfer(tab, null);s = sumCount();}}}// 树化的过程中同样是锁头结点private final void treeifyBin(Node<K,V>[] tab, int index) {Node<K,V> b; int n, sc;if (tab != null) {if ((n = tab.length) < MIN_TREEIFY_CAPACITY)tryPresize(n << 1);else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {synchronized (b) {if (tabAt(tab, index) == b) {TreeNode<K,V> hd = null, tl = null;for (Node<K,V> e = b; e != null; e = e.next) {TreeNode<K,V> p =new TreeNode<K,V>(e.hash, e.key, e.val,null, null);if ((p.prev = tl) == null)hd = p;elsetl.next = p;tl = p;}setTabAt(tab, index, new TreeBin<K,V>(hd));}}}}}
initTable
-
五treeifyBin
// 树化的过程中同样是锁头结点private final void treeifyBin(Node<K,V>[] tab, int index) {Node<K,V> b; int n, sc;if (tab != null) {//必须大于 64才会进行树化 否则会进行扩容if ((n = tab.length) < MIN_TREEIFY_CAPACITY)tryPresize(n << 1);else if ((b = tabAt(tab, index)) != null && b.hash >= 0) {//这里如果插入过程中发生了根节点的变动 这里是将根节点的值进行了改变,而不是对象 所以锁根节点并未失效synchronized (b) {if (tabAt(tab, index) == b) {TreeNode<K,V> hd = null, tl = null;for (Node<K,V> e = b; e != null; e = e.next) {TreeNode<K,V> p =new TreeNode<K,V>(e.hash, e.key, e.val,null, null);if ((p.prev = tl) == null)hd = p;elsetl.next = p;tl = p;}//红黑树插入 在构造函数之中setTabAt(tab, index, new TreeBin<K,V>(hd));}}}}}
六 addCount
```java // 数量的统计
private final void addCount(long x, int check) { CounterCell[] as; long b, s; //这里一旦发生过并发冲突之后就不会添加baseCount了 就会直接进入下边的流程 if ((as = counterCells) != null ||//这里是并发的情况下可能会设置失败 会进入下边的流程!U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) {CounterCell a; long v; int m;boolean uncontended = true;if (as == null || (m = as.length - 1) < 0 ||(a = as[ThreadLocalRandom.getProbe() & m]) == null ||!(uncontended =U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))) {fullAddCount(x, uncontended);return;}if (check <= 1)return;s = sumCount();
} if (check >= 0) {
Node<K,V>[] tab, nt; int n, sc;//这里使用while循环主要是避免并发量高的时候连续进行扩容 所以是这样的while (s >= (long)(sc = sizeCtl) && (tab = table) != null &&(n = tab.length) < MAXIMUM_CAPACITY) {int rs = resizeStamp(n);//当出现并发的时候会进入这里 这里没看懂if (sc < 0) {if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 ||sc == rs + MAX_RESIZERS || (nt = nextTable) == null ||transferIndex <= 0)break;if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1))transfer(tab, nt);}else if (U.compareAndSwapInt(this, SIZECTL, sc,(rs << RESIZE_STAMP_SHIFT) + 2))transfer(tab, null);s = sumCount();}
} }
-
private final void fullAddCount(long x, boolean wasUncontended) {int h;//这里是获得当前线程的一个随机值if ((h = ThreadLocalRandom.getProbe()) == 0) {ThreadLocalRandom.localInit(); // force initializationh = ThreadLocalRandom.getProbe();wasUncontended = true;}boolean collide = false; // True if last slot nonemptyfor (;;) {CounterCell[] as; CounterCell a; int n; long v;if ((as = counterCells) != null && (n = as.length) > 0) {//这里对应位置 CounterCell 的值为null 则新创建if ((a = as[(n - 1) & h]) == null) {//这里使用 cellsBusy 锁避免并发问题 先判断能否访问,不能的话会回到for循环的开始继续执行if (cellsBusy == 0) { // Try to attach new CellCounterCell r = new CounterCell(x); // Optimistic createif (cellsBusy == 0 &&//锁住 自旋锁U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {boolean created = false;try { // Recheck under lockCounterCell[] rs; int m, j;if ((rs = counterCells) != null &&(m = rs.length) > 0 &&rs[j = (m - 1) & h] == null) {//将值赋值进去rs[j] = r;created = true;}} finally {cellsBusy = 0;}if (created)break;continue; // Slot is now non-empty}}collide = false;}//这里判断如果不进行累加 则直接在原来的CounterCell 上CAS的方式更新对应的值else if (!wasUncontended) // CAS already known to failwasUncontended = true; // Continue after rehashelse if (U.compareAndSwapLong(a, CELLVALUE, v = a.value, v + x))break;//下边的代码是如果当前 CounterCell超过NCPU数量 则会进行扩容 扩容为两倍else if (counterCells != as || n >= NCPU)collide = false; // At max size or staleelse if (!collide)collide = true;else if (cellsBusy == 0 &&U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {try {if (counterCells == as) {// Expand table unless stale//具体扩容操作并赋值进入CounterCell[] rs = new CounterCell[n << 1];for (int i = 0; i < n; ++i)rs[i] = as[i];counterCells = rs;}} finally {cellsBusy = 0;}collide = false;continue; // Retry with expanded table}h = ThreadLocalRandom.advanceProbe(h);}// 这里是初始化 counterCells的过程 默认长度是2 cellsBusy 是控制并行访问的else if (cellsBusy == 0 && counterCells == as &&U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) {boolean init = false;try { // Initialize tableif (counterCells == as) {CounterCell[] rs = new CounterCell[2];//这里会把数量存储到 CounterCell中rs[h & 1] = new CounterCell(x);counterCells = rs;init = true;}} finally {cellsBusy = 0;}if (init)break;}else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x))break; // Fall back on using base}}
对应的结构如下所示<br /><a name="QP9qS"></a># 七 transfer```javaprivate final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {int n = tab.length, stride;//这里相当于是计算cpu核心数 看最多几个线程同时进行扩容 这里假设计算的结果是2if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)stride = MIN_TRANSFER_STRIDE; // subdivide range// 这里是初始化操作 初始化下一个数组if (nextTab == null) { // initiatingtry {@SuppressWarnings("unchecked")Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];nextTab = nt;} catch (Throwable ex) { // try to cope with OOMEsizeCtl = Integer.MAX_VALUE;return;}nextTable = nextTab;transferIndex = n;}int nextn = nextTab.length;//正在扩容的节点会被赋值 fwdForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);boolean advance = true;boolean finishing = false; // to ensure sweep before committing nextTab//bound的作用相当于为每个线程分区,扩容是按照分区进行的for (int i = 0, bound = 0;;) {Node<K,V> f; int fh;//这里while循环的作用主要是找到当前线程可扩容的区域while (advance) {int nextIndex, nextBound;if (--i >= bound || finishing)advance = false;else if ((nextIndex = transferIndex) <= 0) {i = -1;advance = false;}//当另一个线程也来找可扩容的区域的时候 区域的划分是使用 TRANSFERINDEX 来进行控制的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}}// 如果扩容的节点是null 则直接赋值fwdelse if ((f = tabAt(tab, i)) == null)advance = casTabAt(tab, i, null, fwd);else if ((fh = f.hash) == MOVED)advance = true; // already processedelse {//扩容的时候锁住当前要扩容的节点synchronized (f) {if (tabAt(tab, i) == f) {Node<K,V> ln, hn;if (fh >= 0) {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;}}if (runBit == 0) {ln = lastRun;hn = null;}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);elsehn = new Node<K,V>(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<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;elseloTail.next = p;loTail = p;++lc;}else {if ((p.prev = hiTail) == null)hi = p;elsehiTail.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;}}}}}}
八 删除
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;//删除位置是空的直接返回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) {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;elsesetTabAt(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));}}}}}if (validated) {if (oldVal != null) {if (value == null)addCount(-1L, -1);return oldVal;}break;}}}return null;}
九 获取
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;}
十 spread
//先保留hash值的高 16位特性,再与int的最大值进行与 相当于或得到int范围内能表示的数字static final int spread(int h) {return (h ^ (h >>> 16)) & HASH_BITS;}// (n - 1) & hash 实际使用 相当于对n-1取余操作


