ThreadLocalMap源码

/*
  static class ThreadLocalMap {
      static class Entry extends WeakReference<ThreadLocal<?>> {
          Object value;
          Entry(ThreadLocal<?> k, Object v) {
              super(k);
              value = v;
          }
      }

      //初始容量,必须是2的幂次(为了利用位运算高效计算角标)
      private static final int INITIAL_CAPACITY = 16;

      //entry数组,根据需要调整,长度必须是2的幂次
      private ThreadLocal.ThreadLocalMap.Entry[] table;

      //数组中元素的个数
      private int size = 0;

      //要调整大小的阈值
      private int threshold; // Default to 0

      //设置调整大小的阈值,维持最少2/3的负载系数
      private void setThreshold(int len) {
          threshold = len * 2 / 3;
      }

      //下一个角标
      private static int nextIndex(int i, int len) {
          return ((i + 1 < len) ? i + 1 : 0);
      }

      //上一个角标
      private static int prevIndex(int i, int len) {
          return ((i - 1 >= 0) ? i - 1 : len - 1);
      }

      //构造一个新的map,最初包含(firstKey,firstValue),threadlocalmap是惰性构造的,所以当我们至少有一个要放入的时候,才创建一个。
      ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
          table = new ThreadLocal.ThreadLocalMap.Entry[INITIAL_CAPACITY];
          int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
          table[i] = new ThreadLocal.ThreadLocalMap.Entry(firstKey, firstValue);
          size = 1;
          setThreshold(INITIAL_CAPACITY);
      }


      //Construct a new map including all Inheritable ThreadLocals
      //from given parent map. Called only by createInheritedMap.
      //@param parentMap the map associated with parent thread.
      private ThreadLocalMap(ThreadLocal.ThreadLocalMap parentMap) {
          ThreadLocal.ThreadLocalMap.Entry[] parentTable = parentMap.table;
          int len = parentTable.length;
          setThreshold(len);
          table = new ThreadLocal.ThreadLocalMap.Entry[len];

          for (int j = 0; j < len; j++) {
              ThreadLocal.ThreadLocalMap.Entry e = parentTable[j];
              if (e != null) {
                  @SuppressWarnings("unchecked")
                  ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
                  if (key != null) {
                      Object value = key.childValue(e.value);
                      ThreadLocal.ThreadLocalMap.Entry c = new ThreadLocal.ThreadLocalMap.Entry(key, value);
                      int h = key.threadLocalHashCode & (len - 1);
                      while (table[h] != null)
                          h = nextIndex(h, len);
                      table[h] = c;
                      size++;
                  }
              }
          }
      }

      //Get the entry associated with key.  This method
      //itself handles only the fast path: a direct hit of existing
      //key. It otherwise relays to getEntryAfterMiss.  This is
      //designed to maximize performance for direct hits, in part
      //by making this method readily inlinable.
      //@param  key the thread local object
      //@return the entry associated with key, or null if no such
      private ThreadLocal.ThreadLocalMap.Entry getEntry(ThreadLocal<?> key) {
          int i = key.threadLocalHashCode & (table.length - 1);
          ThreadLocal.ThreadLocalMap.Entry e = table[i];
          if (e != null && e.get() == key)
              return e;
          else
              return getEntryAfterMiss(key, i, e);
      }

      //Version of getEntry method for use when key is not found in
      //its direct hash slot.
      //@param  key the thread local object
      //@param  i the table index for key's hash code
      //@param  e the entry at table[i]
      //@return the entry associated with key, or null if no such
      private ThreadLocal.ThreadLocalMap.Entry getEntryAfterMiss(ThreadLocal<?> key, int i, ThreadLocal.ThreadLocalMap.Entry e) {
          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;

          while (e != null) {
              ThreadLocal<?> k = e.get();
              if (k == key)
                  return e;
              if (k == null)
                  expungeStaleEntry(i);
              else
                  i = nextIndex(i, len);
              e = tab[i];
          }
          return null;
      }

      //Set the value associated with key.
      //@param key the thread local object
      //@param value the value to be set
      private void set(ThreadLocal<?> key, Object value) {

          // We don't use a fast path as with get() because it is at
          // least as common to use set() to create new entries as
          // it is to replace existing ones, in which case, a fast
          // path would fail more often than not.

          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;
          int i = key.threadLocalHashCode & (len-1);

          for (ThreadLocal.ThreadLocalMap.Entry e = tab[i];
               e != null;
               e = tab[i = nextIndex(i, len)]) {
              ThreadLocal<?> k = e.get();

              if (k == key) {
                  e.value = value;
                  return;
              }

              if (k == null) {
                  replaceStaleEntry(key, value, i);
                  return;
              }
          }

          tab[i] = new ThreadLocal.ThreadLocalMap.Entry(key, value);
          int sz = ++size;
          if (!cleanSomeSlots(i, sz) && sz >= threshold)
              rehash();
      }

      //Remove the entry for key.
      private void remove(ThreadLocal<?> key) {
          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;
          int i = key.threadLocalHashCode & (len-1);
          for (ThreadLocal.ThreadLocalMap.Entry e = tab[i];
               e != null;
               e = tab[i = nextIndex(i, len)]) {
              if (e.get() == key) {
                  e.clear();
                  expungeStaleEntry(i);
                  return;
              }
          }
      }

      //Replace a stale entry encountered during a set operation
      //with an entry for the specified key.  The value passed in
      //the value parameter is stored in the entry, whether or not
      //an entry already exists for the specified key.
      //
      //As a side effect, this method expunges all stale entries in the
      //"run" containing the stale entry.  (A run is a sequence of entries
      //between two null slots.)
      //
      //@param  key the key
      //@param  value the value to be associated with key
      //@param  staleSlot index of the first stale entry encountered while
      //        searching for key.
      //当设置值时通过key计算得到的角标位置已经存在一个空键entry,将其替换
      //作为一个副作用,这个方法会删除本次“run”中所有空键entry,一个“run”是一个entry序列,在两个null entry之间。
      private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                     int staleSlot) {
          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;
          ThreadLocal.ThreadLocalMap.Entry e;

          // Back up to check for prior stale entry in current run.
          // We clean out whole runs at a time to avoid continual
          // incremental rehashing due to garbage collector freeing
          // up refs in bunches (i.e., whenever the collector runs).
          int slotToExpunge = staleSlot;
          for (int i = prevIndex(staleSlot, len);
               (e = tab[i]) != null;
               i = prevIndex(i, len))
              if (e.get() == null)
                  slotToExpunge = i;

          // Find either the key or trailing null slot of run, whichever
          // occurs first
          for (int i = nextIndex(staleSlot, len);
               (e = tab[i]) != null;
               i = nextIndex(i, len)) {
              ThreadLocal<?> k = e.get();

              // If we find key, then we need to swap it
              // with the stale entry to maintain hash table order.
              // The newly stale slot, or any other stale slot
              // encountered above it, can then be sent to expungeStaleEntry
              // to remove or rehash all of the other entries in run.
              if (k == key) {
                  e.value = value;

                  tab[i] = tab[staleSlot];
                  tab[staleSlot] = e;

                  // Start expunge at preceding stale entry if it exists
                  if (slotToExpunge == staleSlot)
                      slotToExpunge = i;
                  cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                  return;
              }

              // If we didn't find stale entry on backward scan, the
              // first stale entry seen while scanning for key is the
              // first still present in the run.
              if (k == null && slotToExpunge == staleSlot)
                  slotToExpunge = i;
          }

          // If key not found, put new entry in stale slot
          tab[staleSlot].value = null;
          tab[staleSlot] = new ThreadLocal.ThreadLocalMap.Entry(key, value);

          // If there are any other stale entries in run, expunge them
          if (slotToExpunge != staleSlot)
              cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
      }

      //Expunge a stale entry by rehashing any possibly colliding entries
      //lying between staleSlot and the next null slot.  This also expunges
      //any other stale entries encountered before the trailing null.  See
      //Knuth, Section 6.4
      //
      //@param staleSlot index of slot known to have null key
      //@return the index of the next null slot after staleSlot
      //(all between staleSlot and this slot will have been checked
      //for expunging).
      //通过重新散列位于staleSlot和下一个空槽之间任何可能发生冲突的条目来删除空键entry
      //这还会清除下一个null之前遇到的任何其他空键entry
      private int expungeStaleEntry(int staleSlot) {
          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;

          // expunge entry at staleSlot
          tab[staleSlot].value = null;
          tab[staleSlot] = null;
          size--;

          // Rehash until we encounter null
          ThreadLocal.ThreadLocalMap.Entry e;
          int i;
          for (i = nextIndex(staleSlot, len);
               (e = tab[i]) != null;
               i = nextIndex(i, len)) {
              ThreadLocal<?> k = e.get();
              if (k == null) {
                  e.value = null;
                  tab[i] = null;
                  size--;
              } else {
                  int h = k.threadLocalHashCode & (len - 1);
                  if (h != i) {
                      tab[i] = null;

                      // Unlike Knuth 6.4 Algorithm R, we must scan until
                      // null because multiple entries could have been stale.
                      while (tab[h] != null)
                          h = nextIndex(h, len);
                      tab[h] = e;
                  }
              }
          }
          return i;
      }

      //Heuristically scan some cells looking for stale entries.
      //This is invoked when either a new element is added, or
      //another stale one has been expunged. It performs a
      //logarithmic number of scans, as a balance between no
      //scanning (fast but retains garbage) and a number of scans
      //proportional to number of elements, that would find all
      //garbage but would cause some insertions to take O(n) time.
      //
      //@param i a position known NOT to hold a stale entry. The
      //scan starts at the element after i.
      //
      //@param n scan control: {@code log2(n)} cells are scanned,
      //unless a stale entry is found, in which case
      //{@code log2(table.length)-1} additional cells are scanned.
      //When called from insertions, this parameter is the number
      //of elements, but when from replaceStaleEntry, it is the
      //table length. (Note: all this could be changed to be either
      //more or less aggressive by weighting n instead of just
      //using straight log n. But this version is simple, fast, and
      //seems to work well.)
      //
      //@return true if any stale entries have been removed.
      //试探性的扫描一些单元格寻找空键entry。当添加新元素或一个空键entry被删时会触发这个操作。
      //这个操作执行对数级的时间复杂度,作为一种平衡,在不操作(快但是有垃圾)和大量扫描之间
      //(和元素数量成正比,可以清除所有垃圾,但是使一些插入操作变为o(n)时间复杂度)。
      private boolean cleanSomeSlots(int i, int n) {
          boolean removed = false;
          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;
          do {
              i = nextIndex(i, len);
              ThreadLocal.ThreadLocalMap.Entry e = tab[i];
              if (e != null && e.get() == null) {
                  n = len;
                  removed = true;
                  i = expungeStaleEntry(i);
              }
          } while ( (n >>>= 1) != 0);
          return removed;
      }

      // Re-pack and/or re-size the table. First scan the entire
      // table removing stale entries. If this doesn't sufficiently
      // shrink the size of the table, double the table size.
      // 重新包装table或重新调整table的大小,首先扫描table,删除空键entry,如果没能充分的缩小table的size,对table进行扩容。
      private void rehash() {
          expungeStaleEntries();

          // Use lower threshold for doubling to avoid hysteresis
          // 低阈值时扩容,避免添加时多次扫描
          if (size >= threshold - threshold / 4)
              resize();
      }

      // Double the capacity of the table.
      // 扩容table为原来的两倍
      private void resize() {
          ThreadLocal.ThreadLocalMap.Entry[] oldTab = table;
          int oldLen = oldTab.length;
          int newLen = oldLen * 2;
          ThreadLocal.ThreadLocalMap.Entry[] newTab = new ThreadLocal.ThreadLocalMap.Entry[newLen];
          int count = 0;

          for (int j = 0; j < oldLen; ++j) {
              ThreadLocal.ThreadLocalMap.Entry e = oldTab[j];
              if (e != null) {
                  ThreadLocal<?> k = e.get();
                  if (k == null) {
                      e.value = null; // Help the GC
                  } else {
                      int h = k.threadLocalHashCode & (newLen - 1);
                      while (newTab[h] != null)
                          h = nextIndex(h, newLen);
                      newTab[h] = e;
                      count++;
                  }
              }
          }

          setThreshold(newLen);
          size = count;
          table = newTab;
      }

      // Expunge all stale entries in the table.
      // 删除table数组中所有的空键entry
      private void expungeStaleEntries() {
          ThreadLocal.ThreadLocalMap.Entry[] tab = table;
          int len = tab.length;
          for (int j = 0; j < len; j++) {
              ThreadLocal.ThreadLocalMap.Entry e = tab[j];
              if (e != null && e.get() == null)
                  expungeStaleEntry(j);
          }
      }
  }

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值