ConcurrentHashMap(2)

第一篇内容: ConcurrentHashMap (1)

transfer 扩容函数
  • MIN_TRANSFER_STRIDE 每次至少扩容 16个hash桶,所以当table的长度小于等于 16时,只会有一个线程在进行扩容工作。
  • 支持多线程进行扩容。
  • 如果在扩容过程中,进行get函数操作,每个bin桶扩容完成后,旧tab的节点位置都会被设置为ForwardingNode(hash值为负)。ForwardingNode 重写了Node节点的find方法,会在NextTable中寻找正确的hash对象。
  • 参考资料https://juejin.cn/post/6844903607901356046
  • 参考资料https://www.jianshu.com/p/487d00afe6ca
/**
 * Minimum number of rebinnings per transfer step. Ranges are
 * subdivided to allow multiple resizer threads.  This value
 * serves as a lower bound to avoid resizers encountering
 * excessive memory contention.  The value should be at least
 * DEFAULT_CAPACITY.
 */
private static final int MIN_TRANSFER_STRIDE = 16;

/**
 * The next table index (plus one) to split while resizing.
 */
// transferIndex 是从数组的右到左进行分析的,由大到小进行递减。
private transient volatile int transferIndex; // nextTab.length / 2;nextTable 的中间index

/**
   * Moves and/or copies the nodes in each bin to new table. See
   * above for explanation.
   */
  private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
      int n = tab.length, stride; // stride 步幅
      // CPU 相关计算
      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<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1]; // new 一个新数组
              nextTab = nt;
          } catch (Throwable ex) {      // try to cope with OOME
              sizeCtl = Integer.MAX_VALUE;
              return;
          }
          nextTable = nextTab;
          transferIndex = n; // n是老的table的length大小, 为初始赋值
      }
      int nextn = nextTab.length;
      ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); // new一个迁移标记未节点
      boolean advance = true; // 是否继续向下迁移
      boolean finishing = false; // to ensure sweep before committing nextTab // 是否结束标记位
      // i 变量是扩容的bin桶的位置。
      // bound 代表本线程执行扩容左侧边界
      for (int i = 0, bound = 0;;) {
          Node<K,V> f; int fh;
          while (advance) {
              int nextIndex, nextBound;
              if (--i >= bound || finishing) // --i 左移一个bin桶位置。 并且保证没有超出bound边界
                  advance = false;
              else if ((nextIndex = transferIndex) <= 0) {
                  i = -1;
                  advance = false;
              }
              // 更新transferIndex值, 最小扩容stride长度的bin桶数量
              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
              }
          }
          else if ((f = tabAt(tab, i)) == null) // 如果table元素为NULL
              advance = casTabAt(tab, i, null, fwd); // 赋值fwd,赋值扩容标记位
          else if ((fh = f.hash) == MOVED) // 其他线程已经在迁移中
              advance = true; // already processed
          else {
              synchronized (f) { // 锁住头结点
                  if (tabAt(tab, i) == f) { // 校验头结点没有变化
                      Node<K,V> ln, hn; // low 和 high Node。 一个链表或者红黑树会被拆分成为两个
                      if (fh >= 0) { // hash值大于 0 的是 链表节点
                          int runBit = fh & n; // 计算最高位,根据最高位是否为0,拆分链表
                          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) { // 高位为0,放在low,否则在high
                              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);
                              else
                                  hn = new Node<K,V>(ph, pk, pv, hn);
                          }
                          setTabAt(nextTab, i, ln); // 插入新table, low 链表
                          setTabAt(nextTab, i + n, hn);  // 插入新table, hight 链表
                          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;
                      }
                  }
              }
          }
      }
  }
helpTransfer 增加扩容线程
/**
 * Helps transfer if a resize is in progress.
 */
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) // transferIndex 扩容的左侧边界已经到0,没有库容意义
                break;
            if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) {
                transfer(tab, nextTab);
                break;
            }
        }
        return nextTab;
    }
    return table;
}
CounterCell
  • 参考LongAdder。统计类
/**
 * A padded cell for distributing counts.  Adapted from LongAdder
 * and Striped64.  See their internal docs for explanation.
 */
// Android-removed: @Contended, this hint is not used by the Android runtime.
//@jdk.internal.vm.annotation.Contended
static final class CounterCell {
    volatile long value;
    CounterCell(long x) { value = x; }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值