1 介绍

ThreadLocal解决线程局部变量统一定义问题,多线程数据不能共享。(InheritableThreadLocal特例除外)不能解决并发问题。解决了:基于类级别的变量定义,每一个线程单独维护自己线程内的变量值(存、取、删的功能)
主要方法:
image.png
image.png

2. ThreadLocal的内部结构

2.1 常见的误解

通常,如果我们不去看源代码的话,我猜ThreadLocal是这样子设计的:每个ThreadLocal类都创建一个Map,然后用线程的ID threadID作为Map的key,要存储的局部变量作为Map的value,这样就能达到各个线程的局部变量隔离的效果。这是最简单的设计方法,JDK最早期的ThreadLocal就是这样设计的。

2.2 核心结构

但是,JDK后面优化了设计方案,现时JDK8 ThreadLocal的设计是:每个Thread维护一个ThreadLocalMap哈希表,这个哈希表的key是ThreadLocal实例本身,value才是真正要存储的值Object。

  • (1) 每个Thread线程内部都有一个Map (ThreadLocalMap)
  • (2) Map里面存储ThreadLocal对象(key)和线程的变量副本(value)
  • (3)Thread内部的Map是由ThreadLocal维护的,由ThreadLocal负责向map获取和设置线程的变量值。
  • (4)对于不同的线程,每次获取副本值时,别的线程并不能获取到当前线程的副本值,形成了副本的隔离,互不干扰。

    2.3 这样设计的好处

    这个设计与我们一开始说的设计刚好相反,这样设计有如下两个优势:

  • (1) 这样设计之后每个Map存储的Entry数量就会变少,因为之前的存储数量由Thread的数量决定,现在是由ThreadLocal的数量决定。

  • (2) 当Thread销毁之后,对应的ThreadLocalMap也会随之销毁,能减少内存的使用。

3 源码解析

3.1 线程唯一标识符

通过上面的介绍,我们可以获知ThreadLocal是以ThreadLocalMap存放key-value形式,而key值又是thread线程标识符,一堆整数。那么这串数字一定是通过某种算法得出,我们来看下面这个例子:

  1. /**
  2. * 生成每个线程唯一的局部标识符
  3. */
  4. public class ThreadId {
  5. // Atomic integer containing the next thread ID to be assigned
  6. private static final AtomicInteger nextId = new AtomicInteger(0);
  7. // Thread local variable containing each thread's ID
  8. private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
  9. @Override
  10. protected Integer initialValue() {
  11. return nextId.getAndIncrement();
  12. }
  13. };
  14. // Returns the current thread's unique ID, assigning it if necessary
  15. public static int get() {
  16. return threadId.get();
  17. }
  18. public static void main(String[] args) {
  19. for (int i = 0; i < 5; i++) {
  20. new Thread(new Runnable() {
  21. public void run() {
  22. System.out.print(threadId.get());
  23. }
  24. }).start();
  25. }
  26. }
  27. }

运行后得到结果:

  1. 01234

而在源码中,则是这样写的。

  1. // 线程标识符HashCode
  2. private final int threadLocalHashCode = nextHashCode();
  3. // 创建一个原子数
  4. private static AtomicInteger nextHashCode =
  5. new AtomicInteger();
  6. private static final int HASH_INCREMENT = 0x61c88647;
  7. private static int nextHashCode() {
  8. return nextHashCode.getAndAdd(HASH_INCREMENT);
  9. }

思考:如果不通过类调用,hashcode会是什么?

  1. public class TreadLocalHashCode {
  2. // 线程标识符HashCode
  3. private final int threadLocalHashCode = nextHashCode();
  4. // 创建一个原子数
  5. private static AtomicInteger nextHashCode =
  6. new AtomicInteger();
  7. private static final int HASH_INCREMENT = 0x61c88647;
  8. private static int nextHashCode() {
  9. return nextHashCode.getAndAdd(HASH_INCREMENT);
  10. }
  11. @Test
  12. public void test(){
  13. TreadLocalHashCode treadLocalHashCode =new TreadLocalHashCode();
  14. System.out.println(threadLocalHashCode);
  15. System.out.println(treadLocalHashCode.threadLocalHashCode);
  16. System.out.println(treadLocalHashCode.threadLocalHashCode & 15);
  17. }
  18. }

结果:

  1. 0
  2. 1640531527
  3. 7

3.2 源码

3.2.1 存储结构

上面已经讲过,其实就是一个map,但这个map又和Map有不同之处,ThreadLocalMap具备了键值对的特性,但没有其底层数组的数据结构。

  1. // 键值对实体的存储结构
  2. // 如果key为null,(entry.get() == null)表示key不再被引用,表示ThreadLocal对象被回收
  3. // 因此这时候entry也可以从table从清除。
  4. static class Entry extends WeakReference<ThreadLocal<?>> {
  5. /** The value associated with this ThreadLocal. */
  6. // 当前线程关联的value,这个value并没有用弱引用追踪
  7. Object value;
  8. /*
  9. * 构造键值对
  10. * k作key,v作value
  11. * 作为key的ThreadLocal会被包装为一个弱引用
  12. */
  13. Entry(ThreadLocal<?> k, Object v) {
  14. super(k);
  15. value = v;
  16. }
  17. }

引用名词说明

类型 回收时间 应用场景
强引用 一直存活,除非GC Roots不可达 所有程序的场景,基本对象,自定义对象等
软引用 内存不足时会被回收 一般用在对内存非常敏感的资源上,用作缓存的场景比较多,例如:网页缓存、图片缓存
弱引用 只能存活到下一次GC前 生命周期很短的对象,例如ThreadLocal中的Key。
虚引用 随时会被回收, 创建了可能很快就会被回收 可能被JVM团队内部用来跟踪JVM的垃圾回收活动

3.2.2 为什么要弱引用

ThreadLocal存储就是一个线程ID,如果线程销毁了,但是这个线程ID依然储存着,那么节点在GC分析中一直处于可达状态,没办法被回收,而程序本身也无法判断是否可以清理节点。

3.2.3 类成员变量与相应方法

  • 成员变量 ```java // Map初始容量,必须为2的冪 private static final int INITIAL_CAPACITY = 16;

// 存储Map中的键值对实体 // 数组长度必须是2的冥 private Entry[] table;

// Map元素数量,可以用于判断table当前使用量是否超过负因子 private int size = 0;

// 扩容阙值,默认为0 private int threshold;

  1. - 方法
  2. ```java
  3. // 设置resize阈值以维持最坏2/3的装载因子
  4. private void setThreshold(int len) {
  5. threshold = len * 2 / 3;
  6. }
  7. // 哈希值发生冲突时,计算下一个哈希值。此处使用线性探测寻址,只是简单地将索引增一。
  8. private static int nextIndex(int i, int len) {
  9. // 如果索引增一后越界,则返回到下标0的地方,循环进行
  10. return ((i + 1 < len) ? i + 1 : 0);
  11. }
  12. // 线性探测,但是逆方向进行,即向前遍历,查找索引上一个索引
  13. private static int prevIndex(int i, int len) {
  14. return ((i - 1 >= 0) ? i - 1 : len - 1);
  15. }

3.2.4 构造函数

重点看一下上面构造函数中的int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);这一行代码。
对于2的幂作为模数取模,可以用&(2n-1)来替代%2n,位运算比取模效率高很多。至于为什么,因为对2^n取模,只要不是低n位对结果的贡献显然都是0,会影响结果的只能是低n位。

  1. // 初始化map,并存储键值对<firstKey, firstValue>
  2. // 构造一个包含firstKey和firstValue的map。
  3. // ThreadLocalMap是惰性构造的,所以只有当至少要往里面放一个元素的时候才会构建它。
  4. ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
  5. // 初始化table数组
  6. table = new Entry[INITIAL_CAPACITY];
  7. // 计算索引,用firstKey的threadLocalHashCode与初始大小16取模得到哈希值
  8. int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
  9. // 设置值
  10. table[i] = new Entry(firstKey, firstValue);
  11. // 设置节点表大小为1
  12. size = 1;
  13. // 设置阈值
  14. setThreshold(INITIAL_CAPACITY);
  15. }

3.2.5 哈希函数

  1. // 0x61c88647为斐波那契散列乘数,哈希得到的结果会比较分散
  2. /*
  3. * HASH_INCREMENT是一个哈希魔数
  4. *
  5. * 观察如下代码:
  6. * int s = 0;
  7. * double n = 4;
  8. * int Max = (int) Math.pow(2, n);
  9. *
  10. * for(int i=s; i<Max+s; i++){
  11. * System.out.println(i*HASH_INCREMENT & (Max-1));
  12. * }
  13. * 这将 随机-均匀 产生 [0,Max-1] 这 Max 个数字。
  14. * 而且,改变s的值,将产生不同的序列
  15. *
  16. * 这与伪随机数的生成原理很像
  17. */
  18. private static final int HASH_INCREMENT = 0x61c88647;
  19. // 原子计数器自增
  20. private static int nextHashCode() {
  21. return nextHashCode.getAndAdd(HASH_INCREMENT);
  22. }

3.2.6 get方法

  1. // 返回当前ThreadLocal对象关联的值
  2. public T get() {
  3. // 返回当前ThreadLocal所在的线程
  4. Thread t = Thread.currentThread();
  5. // 返回当前线程t持有的map
  6. ThreadLocalMap map = getMap(t);
  7. // 如果map不为null,返回其键值对中保存的calue
  8. if (map != null) {
  9. ThreadLocalMap.Entry e = map.getEntry(this);
  10. if (e != null) {
  11. @SuppressWarnings("unchecked")
  12. T result = (T)e.value;
  13. return result;
  14. }
  15. }
  16. // 如果map为空,或者map不空,但是还没有存储当前的ThreadLocalMap对象,则执行以下逻辑
  17. /*
  18. * 初始化map,并存储键值对<key, value>,最后返回value
  19. * 其中,key是当前的ThreadLocal对象,value是为当前的ThreadLocal对象关联的初值
  20. */
  21. return setInitialValue();
  22. }
  23. // 初始化map,并存储键值对<key, value>,最后返回value
  24. // 其中,key是当前的ThreadLocal对象,value是为当前的ThreadLocal对象关联的初值
  25. private T setInitialValue() {
  26. // 获取为ThreadLocal对象设置关联的初值
  27. T value = initialValue();
  28. Thread t = Thread.currentThread();
  29. // 返回当前线程t持有的map
  30. ThreadLocalMap map = getMap(t);
  31. if (map != null)
  32. map.set(this, value);
  33. else
  34. // 为当前线程初始化map,并存储键值对<t, value>
  35. createMap(t, value);
  36. // 如果是TerminatingThreadLocal的ThreadLocal,需要将其注册到TerminatingThreadLocal的静态容器中以便后续处理
  37. // if(this instanceof TerminatingThreadLocal) {
  38. // TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
  39. // }
  40. return value;
  41. }
  42. // 为当前线程初始化map,并存储键值对<this, firstValue>
  43. void createMap(Thread t, T firstValue) {
  44. t.threadLocals = new ThreadLocalMap(this, firstValue);
  45. }
  46. // 返回当前线程thread持有的map
  47. ThreadLocalMap getMap(Thread t) {
  48. return t.threadLocals;
  49. }
  50. // 类似HashMap。
  51. // 进行元素存取时,要清理遇到的垃圾值,且合并原先紧密相邻的元素(除去垃圾值会造成新空槽)
  52. static class ThreadLocalMap {
  53. // 省略多余代码
  54. // 返回key关联的键值对实体
  55. private Entry getEntry(ThreadLocal<?> key) {
  56. int i = key.threadLocalHashCode & (table.length - 1);
  57. Entry e = table[i];
  58. if (e != null && e.get() == key)
  59. return e;
  60. else
  61. // 从i开始向后遍历找到键值对实体
  62. return getEntryAfterMiss(key, i, e);
  63. }
  64. // 从i开始向后遍历找到键值对实体
  65. private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
  66. Entry[] tab = table;
  67. int len = tab.length;
  68. // 基于线性探测法不断向后探测直到遇到空entry。
  69. while (e != null) {
  70. ThreadLocal<?> k = e.get();
  71. if (k == key)
  72. return e;
  73. // 遇到了垃圾值
  74. if (k == null)
  75. // 从索引i开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑
  76. // 该entry对应的ThreadLocal已经被回收,调用expungeStaleEntry来清理无效的entry
  77. expungeStaleEntry(i);
  78. else
  79. i = nextIndex(i, len);
  80. e = tab[i];
  81. }
  82. return null;
  83. }
  84. /*
  85. * 从索引staleSlot开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑
  86. * 返回值是那个终止遍历过程的空槽下标
  87. *
  88. * 执行过程:
  89. * 1. 清理staleSlot中的垃圾值
  90. * 2. 遍历staleSlot后面的元素,直到遇见Entry数组中的空槽(即tab[i]==null)才停止。遍历过程中:
  91. * 2.1 清理遇到的垃圾值
  92. * 2.2 遇到“错位”的元素,将其向前放置在离“理想位置”最近的地方
  93. * 换句话说,经过2.2的操作后,从“理想位置”出发查找某个元素,只要该元素是存在的,
  94. * 那么在找到它的过程中,路过的Entry元素是连成一片的。
  95. * 理解这一点很重要,这是理解set方法的基础之一。
  96. */
  97. private int expungeStaleEntry(int staleSlot) {
  98. Entry[] tab = table;
  99. int len = tab.length;
  100. // expunge entry at staleSlot
  101. // 索引staleSlot处本身标识的就是一个垃圾值,所以需要首先清理掉
  102. // 因为entry对应的ThreadLocal已经被回收,value设为null,显式断开强引用
  103. tab[staleSlot].value = null;
  104. // 显式设置该entry为null,以便垃圾回收
  105. tab[staleSlot] = null;
  106. // size减1,置空后table的被使用量减1
  107. size--;
  108. // Rehash until we encounter null
  109. Entry e;
  110. int i;
  111. // 继续往后遍历连续的Entry数组,直到遇见一个空槽后停止遍历
  112. for (i = nextIndex(staleSlot, len);
  113. (e = tab[i]) != null;
  114. i = nextIndex(i, len)) {
  115. ThreadLocal<?> k = e.get();
  116. // 如果当前Entry已经不包含ThreadLocal,说明这是个垃圾值,需要清理
  117. if (k == null) {
  118. e.value = null;
  119. tab[i] = null;
  120. size--;
  121. } else {
  122. // 该ThreadLocal对象的“理想位置”
  123. // 对于还没有被回收的情况,需要做一次rehash。
  124. // 如果对应的ThreadLocal的ID对len取模出来的索引h不为当前位置i,
  125. // 则从h向后线性探测到第一个空的slot,把当前的entry给挪过去。
  126. int h = k.threadLocalHashCode & (len - 1);
  127. // 遇到“错位”的元素
  128. if (h != i) {
  129. // 将当前位置置空
  130. tab[i] = null;
  131. // Unlike Knuth 6.4 Algorithm R, we must scan until
  132. // null because multiple entries could have been stale.
  133. // 将其向前放置在离“理想位置”最近的地方
  134. /*
  135. * 在原代码的这里有句注释值得一提,原注释如下:
  136. *
  137. * Unlike Knuth 6.4 Algorithm R, we must scan until
  138. * null because multiple entries could have been stale.
  139. *
  140. * 这段话提及了Knuth高德纳的著作TAOCP(《计算机程序设计艺术》)的6.4章节(散列)
  141. * 中的R算法。R算法描述了如何从使用线性探测的散列表中删除一个元素。
  142. * R算法维护了一个上次删除元素的index,当在非空连续段中扫到某个entry的哈希值取模后的索引
  143. * 还没有遍历到时,会将该entry挪到index那个位置,并更新当前位置为新的index,
  144. * 继续向后扫描直到遇到空的entry。
  145. *
  146. * ThreadLocalMap因为使用了弱引用,所以其实每个slot的状态有三种也即
  147. * 有效(value未回收),无效(value已回收),空(entry==null)。
  148. * 正是因为ThreadLocalMap的entry有三种状态,所以不能完全套高德纳原书的R算法。
  149. *
  150. * 因为expungeStaleEntry函数在扫描过程中还会对无效slot清理将之转为空slot,
  151. * 如果直接套用R算法,可能会出现具有相同哈希值的entry之间断开(中间有空entry)。
  152. */
  153. while (tab[h] != null)
  154. h = nextIndex(h, len);
  155. // 将该ThreadLocal对象放进去
  156. tab[h] = e;
  157. /* 这一堆操作目的是让元素存储下标更接近其计算出的哈希值 */
  158. }
  159. }
  160. }
  161. // 返回staleSlot之后第一个空的slot索引
  162. return i;
  163. }
  164. }

3.2.7 set方法

  1. // 为当前ThreadLocal对象关联value值
  2. public void set(T value) {
  3. // 返回当前ThreadLocal所在的线程
  4. Thread t = Thread.currentThread();
  5. // 返回当前线程持有的map
  6. ThreadLocalMap map = getMap(t);
  7. // 如果map不为空,则直接存储<ThreadLocal, T>键值对
  8. if (map != null)
  9. map.set(this, value);
  10. else
  11. // 否则,需要为当前线程初始化map,并存储键值对<this, firstValue>
  12. // 1)当前线程Thread 不存在ThreadLocalMap对象
  13. // 2)则调用createMap进行ThreadLocalMap对象的初始化
  14. // 3)并将此实体entry作为第一个值存放至ThreadLocalMap中
  15. createMap(t, value);
  16. }
  17. // 返回当前线程thread持有的map
  18. ThreadLocalMap getMap(Thread t) {
  19. return t.threadLocals;
  20. }
  21. // 为当前线程初始化map,并存储键值对<this, firstValue>
  22. void createMap(Thread t, T firstValue) {
  23. t.threadLocals = new ThreadLocalMap(this, firstValue);
  24. }
  25. // 类似HashMap。
  26. // 进行元素存取时,要清理遇到的垃圾值,且合并原先紧密相邻的元素(除去垃圾值会造成新空槽)
  27. static class ThreadLocalMap {
  28. // 在map中存储键值对<key, value>
  29. private void set(ThreadLocal<?> key, Object value) {
  30. // We don't use a fast path as with get() because it is at
  31. // least as common to use set() to create new entries as
  32. // it is to replace existing ones, in which case, a fast
  33. // path would fail more often than not.
  34. Entry[] tab = table;
  35. int len = tab.length;
  36. // 当前ThreadLocal的哈希值(理想位置),需要考虑一个线程有多个ThreadLocal的情形
  37. int index = key.threadLocalHashCode & (len-1);
  38. // 遍历一段连续的元素,以查找匹配的ThreadLocal对象
  39. for (Entry e = tab[index];
  40. e != null;
  41. e = tab[index = nextIndex(index, len)]) {
  42. // 获取该哈希值处的ThreadLocal对象
  43. ThreadLocal<?> k = e.get();
  44. // 键值ThreadLocal匹配,直接更改map中的value
  45. if (k == key) {
  46. e.value = value;
  47. return;
  48. }
  49. /*
  50. * 如果当前位置未找到匹配的ThreadLocal,就一直遍历Entry(由于哈希值存在碰撞问题,所以可能初次计算出的哈希值没法用)
  51. * 向后遍历的过程中,会出现以下情形:
  52. * 1. 找到了匹配的ThreadLocal,那么执行上面的if语句,并退出
  53. * 2. 遇到了一个垃圾值
  54. */
  55. if (k == null) {
  56. /*
  57. * 继续从索引index开始遍历map,给ThreadLocal对象安排合适的位置
  58. * 安排完ThreadLocal对象后,还会清理一部分垃圾
  59. */
  60. replaceStaleEntry(key, value, index);
  61. return;
  62. }
  63. }
  64. // 直到遇见了空槽也没找到匹配的ThreadLocal对象,那么在此空槽处安排ThreadLocal对象和缓存的value
  65. tab[index] = new Entry(key, value);
  66. int sz = ++size;
  67. // 从下标i开始向后遍历,清理一部分垃圾值,清理过后元素依然是紧凑的
  68. boolean isRemoved = cleanSomeSlots(index, sz);
  69. // 如果没有元素被清理,那么就要检查当前元素数量是否超过了容量阙值,以便决定是否扩容
  70. if(!isRemoved && sz >= threshold) {
  71. // 需要扩容,扩容的过程也是对所有的key重新哈希的过程
  72. rehash();
  73. }
  74. }
  75. /*
  76. * 从索引staleSlot开始遍历map,给ThreadLocal对象安排合适的位置
  77. * 安排完ThreadLocal对象后,还会清理一部分垃圾
  78. *
  79. * key代表待匹配的ThreadLocal对象,value就是键值对里的值
  80. * staleSlot是遍历连续的元素去匹配ThreadLocal对象的过程中遇到的第一个垃圾值
  81. */
  82. private void replaceStaleEntry(ThreadLocal<?> key, Object value,
  83. int staleSlot) {
  84. Entry[] tab = table;
  85. int len = tab.length;
  86. Entry e;
  87. // Back up to check for prior stale entry in current run.
  88. // We clean out whole runs at a time to avoid continual
  89. // incremental rehashing due to garbage collector freeing
  90. // up refs in bunches (i.e., whenever the collector runs).
  91. // 向前扫描,查找最前的一个无效slot
  92. int slotToExpunge = staleSlot;
  93. // 从staleSlot开始往前遍历一段连续的元素,找出最早出现垃圾值的位置
  94. for (int i = prevIndex(staleSlot, len);
  95. (e = tab[i]) != null;
  96. i = prevIndex(i, len))
  97. // 遇到了垃圾值
  98. if (e.get() == null)
  99. // slotToExpunge用来记录在索引staleSlot之前的那段连续的元素中最早出现的垃圾值的下标
  100. slotToExpunge = i;
  101. // Find either the key or trailing null slot of run, whichever
  102. // occurs first
  103. /*
  104. * 至此,i指向了一个空槽
  105. * 如果slotToExpunge == staleSlot,说明在(i, staleSlot)这段没有垃圾值
  106. * 如果slotToExpunge != staleSlot,说明在(i, staleSlot)这段有垃圾值,且从i开始遇到的第一个垃圾值是slotToExpunge
  107. *
  108. * 注:在此要想象一个循环链表,(i, staleSlot)只代表一段区域,i和staleSlot的值谁大谁小并不确定
  109. */
  110. // 从staleSlot开始向后遍历一段连续的元素,找出最晚出现垃圾值的位置
  111. for (int i = nextIndex(staleSlot, len);
  112. (e = tab[i]) != null;
  113. i = nextIndex(i, len)) {
  114. ThreadLocal<?> k = e.get();
  115. // If we find key, then we need to swap it
  116. // with the stale entry to maintain hash table order.
  117. // The newly stale slot, or any other stale slot
  118. // encountered above it, can then be sent to expungeStaleEntry
  119. // to remove or rehash all of the other entries in run.
  120. // 找到了匹配的ThreadLocal对象
  121. if (k == key) {
  122. // 直接设置值
  123. e.value = value;
  124. /*
  125. * 将ThreadLocal对象尽量往前挪,已知离理想位置最近且安全的“空”位置就是staleSlot
  126. * 与此同时,垃圾值后移,稍后被清理
  127. */
  128. tab[i] = tab[staleSlot];
  129. tab[staleSlot] = e;
  130. // Start expunge at preceding stale entry if it exists
  131. if (slotToExpunge == staleSlot)
  132. // 可能需要更新slotToExpunge的位置(往后设置)
  133. slotToExpunge = i;
  134. // 从索引slotToExpunge开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑,返回值是那个终止遍历过程的空槽下标
  135. int stop = expungeStaleEntry(slotToExpunge);
  136. // 从下标stop开始向后遍历,清理一部分垃圾值
  137. cleanSomeSlots(stop, len);
  138. return;
  139. }
  140. // If we didn't find stale entry on backward scan, the
  141. // first stale entry seen while scanning for key is the
  142. // first still present in the run.
  143. // 发现新的垃圾值,将slotToExpunge设置到靠后一点的位置
  144. if (k == null && slotToExpunge == staleSlot)
  145. slotToExpunge = i;
  146. }
  147. /*
  148. * 至此,j指向了一个空槽
  149. * 如果slotToExpunge == staleSlot,说明在(staleSlot, j)这段没有垃圾值
  150. * 如果slotToExpunge != staleSlot,有两种可能:
  151. * 1.slotToExpunge在staleSlot之前最远的垃圾值处
  152. * 2.slotToExpunge在staleSlot之后最近的垃圾值处
  153. *
  154. * 注1:这里的最远最近都是建立在连续元素的基础上讨论的,连续元素的意思是中间没有空槽(但可能有垃圾值)
  155. *
  156. * 注2:同上,在此也要想象一个循环链表
  157. */
  158. // If key not found, put new entry in stale slot
  159. // 如果没有找到匹配的ThreadLocal对象,就在staleSlot处创建新的节点
  160. tab[staleSlot].value = null; // 释放值的引用
  161. tab[staleSlot] = new Entry(key, value); // 存储键值对
  162. // If there are any other stale entries in run, expunge them
  163. // 清理标记处的垃圾值
  164. if (slotToExpunge != staleSlot) {
  165. // 从索引slotToExpunge开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑,返回值是那个终止遍历过程的空槽下标
  166. int stop = expungeStaleEntry(slotToExpunge);
  167. // 从下标stop开始向后遍历,捎带清理一部分垃圾值,清理过后元素依然是紧凑的
  168. cleanSomeSlots(stop, len);
  169. }
  170. }
  171. // 从下标i开始向后遍历,清理一部分垃圾值,清理过后元素依然是紧凑的
  172. private boolean cleanSomeSlots(int i, int n) {
  173. boolean removed = false;
  174. ThreadLocal.ThreadLocalMap.Entry[] tab = table;
  175. int len = tab.length;
  176. do {
  177. // i在任何情况下自己都不会是一个无效slot,所以从下一个开始判断
  178. i = nextIndex(i, len);
  179. ThreadLocal.ThreadLocalMap.Entry e = tab[i];
  180. // 遇到了垃圾值
  181. if (e != null && e.get() == null) {
  182. // 扩大扫描控制因子
  183. n = len;
  184. removed = true;
  185. // 从索引i开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑,返回值是那个终止遍历过程的空槽下标
  186. i = expungeStaleEntry(i);
  187. }
  188. /*
  189. * 执行log2n次循环
  190. *
  191. * 关于这个扫描次数控制:
  192. * 1. 如果扫描过程中没有遇到垃圾值,那么扫描log2n个元素就结束了,不往下找了
  193. * 2. 只要途中遇到某个垃圾值,扫描次数和范围就会扩大,其中:
  194. * n=len扩大了扫描次数,expungeStaleEntry()方法扩大了扫描范围
  195. */
  196. } while ( (n >>>= 1) != 0);
  197. return removed;
  198. }
  199. // 扩容并再哈希
  200. private void rehash() {
  201. // 再次清理表中所有垃圾值
  202. expungeStaleEntries();
  203. // Use lower threshold for doubling to avoid hysteresis
  204. /**
  205. * threshold = 2/3 * len
  206. * 所以threshold - threshold / 4 = 1en/2
  207. * 这里主要是因为上面做了一次全清理所以size减小,需要进行判断。
  208. * 判断的时候把阈值调低了。
  209. */
  210. if (size >= threshold - threshold / 4)
  211. // 迫不得已,必须扩容
  212. resize();
  213. }
  214. // 扩容,扩大为原来的2倍(这样保证了长度为2的冥)
  215. private void resize() {
  216. Entry[] oldTab = table;
  217. int oldLen = oldTab.length;
  218. int newLen = oldLen * 2;
  219. Entry[] newTab = new Entry[newLen];
  220. int count = 0;
  221. for (int j = 0; j < oldLen; ++j) {
  222. Entry e = oldTab[j];
  223. if (e != null) {
  224. ThreadLocal<?> k = e.get();
  225. // 仍然有垃圾值,则标记清理该元素的引用,以便GC回收
  226. if (k == null) {
  227. e.value = null; // Help the GC
  228. } else {
  229. // 计算新的“理想位置”
  230. int h = k.threadLocalHashCode & (newLen - 1);
  231. // 如果发生冲突,使用线性探测往后寻找合适的位置
  232. while (newTab[h] != null)
  233. h = nextIndex(h, newLen);
  234. newTab[h] = e;
  235. count++;
  236. }
  237. }
  238. }
  239. // 设置新的容量阙值
  240. setThreshold(newLen);
  241. size = count;
  242. table = newTab;
  243. }
  244. }

3.2.8 完整源码

  1. package java.lang;
  2. import java.lang.ref.*;
  3. import java.util.Objects;
  4. import java.util.concurrent.atomic.AtomicInteger;
  5. import java.util.function.Supplier;
  6. /**
  7. * This class provides thread-local variables. These variables differ from
  8. * their normal counterparts in that each thread that accesses one (via its
  9. * {@code get} or {@code set} method) has its own, independently initialized
  10. * copy of the variable. {@code ThreadLocal} instances are typically private
  11. * static fields in classes that wish to associate state with a thread (e.g.,
  12. * a user ID or Transaction ID).
  13. *
  14. * <p>For example, the class below generates unique identifiers local to each
  15. * thread.
  16. * A thread's id is assigned the first time it invokes {@code ThreadId.get()}
  17. * and remains unchanged on subsequent calls.
  18. * <pre>
  19. * import java.util.concurrent.atomic.AtomicInteger;
  20. *
  21. * public class ThreadId {
  22. * // Atomic integer containing the next thread ID to be assigned
  23. * private static final AtomicInteger nextId = new AtomicInteger(0);
  24. *
  25. * // Thread local variable containing each thread's ID
  26. * private static final ThreadLocal&lt;Integer&gt; threadId =
  27. * new ThreadLocal&lt;Integer&gt;() {
  28. * &#64;Override protected Integer initialValue() {
  29. * return nextId.getAndIncrement();
  30. * }
  31. * };
  32. *
  33. * // Returns the current thread's unique ID, assigning it if necessary
  34. * public static int get() {
  35. * return threadId.get();
  36. * }
  37. * }
  38. * </pre>
  39. * <p>Each thread holds an implicit reference to its copy of a thread-local
  40. * variable as long as the thread is alive and the {@code ThreadLocal}
  41. * instance is accessible; after a thread goes away, all of its copies of
  42. * thread-local instances are subject to garbage collection (unless other
  43. * references to these copies exist).
  44. *
  45. * @author Josh Bloch and Doug Lea
  46. * @since 1.2
  47. */
  48. /*
  49. * 线程局部缓存:为线程缓存数据,将数据本地化(脱离共享)
  50. *
  51. * 原理:
  52. * 1. 每个线程由一个ThreadLocalMap属性,本质就是一个map
  53. * 2. map里面存储的<key, value>称为键值对,存储键值对时需要先求取哈希值
  54. * 由于哈希值会出现冲突,所以会造成“错位”元素的出现(元素“理想位置”和实际存储位置不一样)
  55. * “理想位置”是指该ThreadLocal对象初次计算出的哈希值
  56. * 如果从“理想位置”到实际存储位置是连续的,这里称该序列是“紧凑”的
  57. * 3. map里存储的key是一个弱引用,其包装了当前线程中构造的ThreadLocal对象
  58. * 这意味着,只要ThreadLocal对象丢掉了强引用,那么在下次GC后,map中的ThreadLocal对象也会被清除
  59. * 对于那些ThreadLocal对象为空的map元素,这里称其为【垃圾值】,稍后会被主动清理
  60. * 4. map里存储的value就是缓存到当前线程的值,这个value没有弱引用去包装,需要专门的释放策略
  61. * 5. 一个线程对应多个ThreadLocal,一个ThreadLocal只对应一个值
  62. *
  63. * 注,关于哈希值碰撞的问题:
  64. * 如果是单线程,因为魔数HASH_INCREMENT的存在,且不断扩容,这里不容易出现碰撞
  65. * 但如果是多线程,哈希值就很容易出现碰撞,因为属性nextHashCode是各线程共享的,会导致生成的标识出现重复
  66. *
  67. * ThreadLocal不能解决线程同步问题。
  68. *
  69. * 每个线程有一个ThreadLocalMap(作为map)。但可以有多个ThreadLocal(作为map中的key)。
  70. *
  71. * ThreadLocal<T> sThreadLocal = new ThreadLocal<>();
  72. * <sThreadLocal, T>形成map的键值对,sThreadLocal作为ThreadLocalMap中的键,用它来查找匹配的值。
  73. */
  74. public class ThreadLocal<T> {
  75. /**
  76. * ThreadLocals rely on per-thread linear-probe hash maps attached
  77. * to each thread (Thread.threadLocals and
  78. * inheritableThreadLocals). The ThreadLocal objects act as keys,
  79. * searched via threadLocalHashCode. This is a custom hash code
  80. * (useful only within ThreadLocalMaps) that eliminates collisions
  81. * in the common case where consecutively constructed ThreadLocals
  82. * are used by the same threads, while remaining well-behaved in
  83. * less common cases.
  84. */
  85. // 线程标识符HashCode
  86. // 如果直接获取,那么结果无论如何都是0
  87. // 需要调用自身类才能获取到计算后的hashcode
  88. // 一个线程可以有多个ThreadLocal实例,各实例之内的原始种子值不相同
  89. // 一个ThreadLocal实例也可被多个线程共享,此时多个线程内看到的原始种子值是相同的
  90. private final int threadLocalHashCode = nextHashCode();
  91. /**
  92. * Creates a thread local variable.
  93. * @see #withInitial(java.util.function.Supplier)
  94. */
  95. // 构造函数
  96. public ThreadLocal() {
  97. }
  98. /**
  99. * The next hash code to be given out. Updated atomically. Starts at
  100. * zero.
  101. */
  102. // 创建一个原子数,开始数为0,由所有ThreadLocal共享,但每次构造一个ThreadLocal实例,其值都会更新
  103. private static AtomicInteger nextHashCode =
  104. new AtomicInteger();
  105. /**
  106. * The difference between successively generated hash codes - turns
  107. * implicit sequential thread-local IDs into near-optimally spread
  108. * multiplicative hash values for power-of-two-sized tables.
  109. */
  110. // 0x61c88647为斐波那契散列乘数,哈希得到的结果会比较分散
  111. /*
  112. * HASH_INCREMENT是一个哈希魔数
  113. *
  114. * 观察如下代码:
  115. * int s = 0;
  116. * double n = 4;
  117. * int Max = (int) Math.pow(2, n);
  118. *
  119. * for(int i=s; i<Max+s; i++){
  120. * System.out.println(i*HASH_INCREMENT & (Max-1));
  121. * }
  122. * 这将 随机-均匀 产生 [0,Max-1] 这 Max 个数字。
  123. * 而且,改变s的值,将产生不同的序列
  124. *
  125. * 这与伪随机数的生成原理很像
  126. */
  127. private static final int HASH_INCREMENT = 0x61c88647;
  128. /**
  129. * Returns the next hash code.
  130. */
  131. // 原子计数器自增
  132. private static int nextHashCode() {
  133. return nextHashCode.getAndAdd(HASH_INCREMENT);
  134. }
  135. /**
  136. * Returns the current thread's "initial value" for this
  137. * thread-local variable. This method will be invoked the first
  138. * time a thread accesses the variable with the {@link #get}
  139. * method, unless the thread previously invoked the {@link #set}
  140. * method, in which case the {@code initialValue} method will not
  141. * be invoked for the thread. Normally, this method is invoked at
  142. * most once per thread, but it may be invoked again in case of
  143. * subsequent invocations of {@link #remove} followed by {@link #get}.
  144. *
  145. * <p>This implementation simply returns {@code null}; if the
  146. * programmer desires thread-local variables to have an initial
  147. * value other than {@code null}, {@code ThreadLocal} must be
  148. * subclassed, and this method overridden. Typically, an
  149. * anonymous inner class will be used.
  150. *
  151. * @return the initial value for this thread-local
  152. */
  153. // 初始化设值的方法,可以被子类覆盖
  154. protected T initialValue() {
  155. return null;
  156. }
  157. /**
  158. * Creates a thread local variable. The initial value of the variable is
  159. * determined by invoking the {@code get} method on the {@code Supplier}.
  160. *
  161. * @param <S> the type of the thread local's value
  162. * @param supplier the supplier to be used to determine the initial value
  163. * @return a new thread local variable
  164. * @throws NullPointerException if the specified supplier is null
  165. * @since 1.8
  166. */
  167. // 返回一个扩展的ThreadLocal,其关联的初值由supplier给出
  168. public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
  169. return new SuppliedThreadLocal<>(supplier);
  170. }
  171. /**
  172. * Returns the value in the current thread's copy of this
  173. * thread-local variable. If the variable has no value for the
  174. * current thread, it is first initialized to the value returned
  175. * by an invocation of the {@link #initialValue} method.
  176. *
  177. * @return the current thread's value of this thread-local
  178. */
  179. // 返回当前ThreadLocal对象关联的值
  180. public T get() {
  181. // 返回当前ThreadLocal所在的线程
  182. Thread t = Thread.currentThread();
  183. // 返回当前线程t持有的map
  184. ThreadLocalMap map = getMap(t);
  185. // 如果map不为null,返回其键值对中保存的calue
  186. if (map != null) {
  187. ThreadLocalMap.Entry e = map.getEntry(this);
  188. if (e != null) {
  189. @SuppressWarnings("unchecked")
  190. T result = (T)e.value;
  191. return result;
  192. }
  193. }
  194. // 如果map为空,或者map不空,但是还没有存储当前的ThreadLocalMap对象,则执行以下逻辑
  195. /*
  196. * 初始化map,并存储键值对<key, value>,最后返回value
  197. * 其中,key是当前的ThreadLocal对象,value是为当前的ThreadLocal对象关联的初值
  198. */
  199. return setInitialValue();
  200. }
  201. /**
  202. * Variant of set() to establish initialValue. Used instead
  203. * of set() in case user has overridden the set() method.
  204. *
  205. * @return the initial value
  206. */
  207. // 初始化map,并存储键值对<key, value>,最后返回value
  208. // 其中,key是当前的ThreadLocal对象,value是为当前的ThreadLocal对象关联的初值
  209. private T setInitialValue() {
  210. // 获取为ThreadLocal对象设置关联的初值
  211. T value = initialValue();
  212. Thread t = Thread.currentThread();
  213. // 返回当前线程t持有的map
  214. ThreadLocalMap map = getMap(t);
  215. if (map != null)
  216. map.set(this, value);
  217. else
  218. // 为当前线程初始化map,并存储键值对<t, value>
  219. createMap(t, value);
  220. // 如果是TerminatingThreadLocal的ThreadLocal,需要将其注册到TerminatingThreadLocal的静态容器中以便后续处理
  221. // if(this instanceof TerminatingThreadLocal) {
  222. // TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
  223. // }
  224. return value;
  225. }
  226. /**
  227. * Sets the current thread's copy of this thread-local variable
  228. * to the specified value. Most subclasses will have no need to
  229. * override this method, relying solely on the {@link #initialValue}
  230. * method to set the values of thread-locals.
  231. *
  232. * @param value the value to be stored in the current thread's copy of
  233. * this thread-local.
  234. */
  235. // 为当前ThreadLocal对象关联value值
  236. public void set(T value) {
  237. // 返回当前ThreadLocal所在的线程
  238. Thread t = Thread.currentThread();
  239. // 返回当前线程持有的map
  240. ThreadLocalMap map = getMap(t);
  241. // 如果map不为空,则直接存储<ThreadLocal, T>键值对
  242. if (map != null)
  243. map.set(this, value);
  244. else
  245. // 否则,需要为当前线程初始化map,并存储键值对<this, firstValue>
  246. // 1)当前线程Thread 不存在ThreadLocalMap对象
  247. // 2)则调用createMap进行ThreadLocalMap对象的初始化
  248. // 3)并将此实体entry作为第一个值存放至ThreadLocalMap中
  249. createMap(t, value);
  250. }
  251. /**
  252. * Removes the current thread's value for this thread-local
  253. * variable. If this thread-local variable is subsequently
  254. * {@linkplain #get read} by the current thread, its value will be
  255. * reinitialized by invoking its {@link #initialValue} method,
  256. * unless its value is {@linkplain #set set} by the current thread
  257. * in the interim. This may result in multiple invocations of the
  258. * {@code initialValue} method in the current thread.
  259. *
  260. * @since 1.5
  261. */
  262. // 清理当前ThreadLocal对象关联的键值对,可以看成是set的逆操作
  263. public void remove() {
  264. ThreadLocalMap m = getMap(Thread.currentThread());
  265. if (m != null)
  266. // 从map中清理当前ThreadLocal对象关联的键值对
  267. m.remove(this);
  268. }
  269. /**
  270. * Get the map associated with a ThreadLocal. Overridden in
  271. * InheritableThreadLocal.
  272. *
  273. * @param t the current thread
  274. * @return the map
  275. */
  276. // 返回当前线程thread持有的map
  277. ThreadLocalMap getMap(Thread t) {
  278. return t.threadLocals;
  279. }
  280. /**
  281. * Create the map associated with a ThreadLocal. Overridden in
  282. * InheritableThreadLocal.
  283. *
  284. * @param t the current thread
  285. * @param firstValue value for the initial entry of the map
  286. */
  287. // 为当前线程初始化map,并存储键值对<this, firstValue>
  288. void createMap(Thread t, T firstValue) {
  289. t.threadLocals = new ThreadLocalMap(this, firstValue);
  290. }
  291. /**
  292. * Factory method to create map of inherited thread locals.
  293. * Designed to be called only from Thread constructor.
  294. *
  295. * @param parentMap the map associated with parent thread
  296. * @return a map containing the parent's inheritable bindings
  297. */
  298. // 构造一个新的map,其包含给定的parentMap中当前所有可继承ThreadLocals,且允许修改parentMap中的值
  299. // 该方法在Thread调用
  300. static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
  301. return new ThreadLocalMap(parentMap);
  302. }
  303. /**
  304. * Method childValue is visibly defined in subclass
  305. * InheritableThreadLocal, but is internally defined here for the
  306. * sake of providing createInheritedMap factory method without
  307. * needing to subclass the map class in InheritableThreadLocal.
  308. * This technique is preferable to the alternative of embedding
  309. * instanceof tests in methods.
  310. */
  311. // 获取parentValue,有时会对其进行加工,主要用于测试,参见子类InheritableThreadLocal等。
  312. T childValue(T parentValue) {
  313. throw new UnsupportedOperationException();
  314. }
  315. /**
  316. * Returns {@code true} if there is a value in the current thread's copy of this thread-local variable, even if that values is {@code null}.
  317. *
  318. * @return {@code true} if current thread has associated value in this thread-local variable; {@code false} if not
  319. */
  320. // 返回true意味着当前ThreadLocal对象没有变成垃圾值
  321. boolean isPresent() {
  322. Thread t = Thread.currentThread();
  323. // 返回当前线程t持有的map
  324. ThreadLocalMap map = getMap(t);
  325. return map != null && map.getEntry(this) != null;
  326. }
  327. /**
  328. * An extension of ThreadLocal that obtains its initial value from
  329. * the specified {@code Supplier}.
  330. */
  331. // ThreadLocal的一个扩展。其ThreadLocal关联的初值由字段supplier给出
  332. static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
  333. private final Supplier<? extends T> supplier;
  334. SuppliedThreadLocal(Supplier<? extends T> supplier) {
  335. this.supplier = Objects.requireNonNull(supplier);
  336. }
  337. @Override
  338. protected T initialValue() {
  339. return supplier.get();
  340. }
  341. }
  342. /**
  343. * ThreadLocalMap is a customized hash map suitable only for
  344. * maintaining thread local values. No operations are exported
  345. * outside of the ThreadLocal class. The class is package private to
  346. * allow declaration of fields in class Thread. To help deal with
  347. * very large and long-lived usages, the hash table entries use
  348. * WeakReferences for keys. However, since reference queues are not
  349. * used, stale entries are guaranteed to be removed only when
  350. * the table starts running out of space.
  351. */
  352. // 类似HashMap。
  353. // 进行元素存取时,要清理遇到的垃圾值,且合并原先紧密相邻的元素(除去垃圾值会造成新空槽)
  354. static class ThreadLocalMap {
  355. /**
  356. * The entries in this hash map extend WeakReference, using
  357. * its main ref field as the key (which is always a
  358. * ThreadLocal object). Note that null keys (i.e. entry.get()
  359. * == null) mean that the key is no longer referenced, so the
  360. * entry can be expunged from table. Such entries are referred to
  361. * as "stale entries" in the code that follows.
  362. */
  363. // 键值对实体的存储结构
  364. // 如果key为null,(entry.get() == null)表示key不再被引用,表示ThreadLocal对象被回收
  365. // 因此这时候entry也可以从table从清除。
  366. static class Entry extends WeakReference<ThreadLocal<?>> {
  367. /** The value associated with this ThreadLocal. */
  368. // 当前线程关联的value,这个value并没有用弱引用追踪
  369. Object value;
  370. /*
  371. * 构造键值对
  372. * k作key,v作value
  373. * 作为key的ThreadLocal会被包装为一个弱引用
  374. */
  375. Entry(ThreadLocal<?> k, Object v) {
  376. super(k);
  377. value = v;
  378. }
  379. }
  380. /**
  381. * The initial capacity -- MUST be a power of two.
  382. */
  383. // Map初始容量,必须为2的冪
  384. private static final int INITIAL_CAPACITY = 16;
  385. /**
  386. * The table, resized as necessary.
  387. * table.length MUST always be a power of two.
  388. */
  389. // 存储Map中的键值对实体
  390. // 数组长度必须是2的冥
  391. private Entry[] table;
  392. /**
  393. * The number of entries in the table.
  394. */
  395. // Map元素数量,可以用于判断table当前使用量是否超过负因子
  396. private int size = 0;
  397. /**
  398. * The next size value at which to resize.
  399. */
  400. private int threshold; // 扩容阙值,默认为0
  401. /**
  402. * Set the resize threshold to maintain at worst a 2/3 load factor.
  403. */
  404. // 定义为长度的2/3
  405. private void setThreshold(int len) {
  406. threshold = len * 2 / 3;
  407. }
  408. /**
  409. * Increment i modulo len.
  410. */
  411. // 哈希值发生冲突时,计算下一个哈希值。此处使用线性探测寻址,只是简单地将索引增一。
  412. private static int nextIndex(int i, int len) {
  413. // 如果索引增一后越界,则返回到下标0的地方,循环进行
  414. return ((i + 1 < len) ? i + 1 : 0);
  415. }
  416. /**
  417. * Decrement i modulo len.
  418. */
  419. // 线性探测,但是逆方向进行,即向前遍历
  420. private static int prevIndex(int i, int len) {
  421. return ((i - 1 >= 0) ? i - 1 : len - 1);
  422. }
  423. /**
  424. * Construct a new map initially containing (firstKey, firstValue).
  425. * ThreadLocalMaps are constructed lazily, so we only create
  426. * one when we have at least one entry to put in it.
  427. */
  428. // 初始化map,并存储键值对<firstKey, firstValue>
  429. ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
  430. // 初始化table
  431. table = new Entry[INITIAL_CAPACITY];
  432. // 计算索引
  433. int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
  434. // 设置值
  435. table[i] = new Entry(firstKey, firstValue);
  436. size = 1;
  437. // 设置阈值
  438. setThreshold(INITIAL_CAPACITY);
  439. }
  440. /**
  441. * Construct a new map including all Inheritable ThreadLocals
  442. * from given parent map. Called only by createInheritedMap.
  443. *
  444. * @param parentMap the map associated with parent thread.
  445. */
  446. // 构造一个新的map,其包含给定的parentMap中当前所有可继承ThreadLocals,且允许修改parentMap中的值。仅由createInheritedMap调用
  447. private ThreadLocalMap(ThreadLocalMap parentMap) {
  448. // 获取父线程的所有Entry
  449. Entry[] parentTable = parentMap.table;
  450. // 获取父线程的Entry数量
  451. int len = parentTable.length;
  452. setThreshold(len);
  453. // ThreadLocalMap使用Entry[] table存储ThreadLocal
  454. table = new Entry[len];
  455. // 挨个复制父线程中map的Entry
  456. for (int j = 0; j < len; j++) {
  457. Entry e = parentTable[j];
  458. if (e != null) {
  459. @SuppressWarnings("unchecked")
  460. ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
  461. if (key != null) {
  462. // 为什么这里不是直接赋值而是使用childValue方法?
  463. // 因为childValue内部是直接将e.value返回的,
  464. // 这样实现的目的可能是为了保证代码最大程度上的拓展性
  465. // 因为可以重写childValue()覆盖
  466. Object value = key.childValue(e.value);
  467. Entry c = new Entry(key, value);
  468. int h = key.threadLocalHashCode & (len - 1);
  469. while (table[h] != null)
  470. h = nextIndex(h, len);
  471. table[h] = c;
  472. size++;
  473. }
  474. }
  475. }
  476. }
  477. /**
  478. * Get the entry associated with key. This method
  479. * itself handles only the fast path: a direct hit of existing
  480. * key. It otherwise relays to getEntryAfterMiss. This is
  481. * designed to maximize performance for direct hits, in part
  482. * by making this method readily inlinable.
  483. *
  484. * @param key the thread local object
  485. * @return the entry associated with key, or null if no such
  486. */
  487. // 返回key关联的键值对实体
  488. private Entry getEntry(ThreadLocal<?> key) {
  489. int i = key.threadLocalHashCode & (table.length - 1);
  490. Entry e = table[i];
  491. if (e != null && e.get() == key)
  492. return e;
  493. else
  494. // 从i开始向后遍历找到键值对实体
  495. return getEntryAfterMiss(key, i, e);
  496. }
  497. /**
  498. * Version of getEntry method for use when key is not found in
  499. * its direct hash slot.
  500. *
  501. * @param key the thread local object
  502. * @param i the table index for key's hash code
  503. * @param e the entry at table[i]
  504. * @return the entry associated with key, or null if no such
  505. */
  506. // 从i开始向后遍历找到键值对实体
  507. private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
  508. Entry[] tab = table;
  509. int len = tab.length;
  510. while (e != null) {
  511. ThreadLocal<?> k = e.get();
  512. if (k == key)
  513. return e;
  514. // 遇到了垃圾值
  515. if (k == null)
  516. // 从索引i开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑
  517. expungeStaleEntry(i);
  518. else
  519. i = nextIndex(i, len);
  520. e = tab[i];
  521. }
  522. return null;
  523. }
  524. /**
  525. * Set the value associated with key.
  526. *
  527. * @param key the thread local object
  528. * @param value the value to be set
  529. */
  530. // 在map中存储键值对<key, value>
  531. private void set(ThreadLocal<?> key, Object value) {
  532. // We don't use a fast path as with get() because it is at
  533. // least as common to use set() to create new entries as
  534. // it is to replace existing ones, in which case, a fast
  535. // path would fail more often than not.
  536. Entry[] tab = table;
  537. int len = tab.length;
  538. // 当前ThreadLocal的哈希值(理想位置),需要考虑一个线程有多个ThreadLocal的情形
  539. int index = key.threadLocalHashCode & (len-1);
  540. // 遍历一段连续的元素,以查找匹配的ThreadLocal对象
  541. for (Entry e = tab[index];
  542. e != null;
  543. e = tab[index = nextIndex(index, len)]) {
  544. // 获取该哈希值处的ThreadLocal对象
  545. ThreadLocal<?> k = e.get();
  546. // 键值ThreadLocal匹配,直接更改map中的value
  547. if (k == key) {
  548. e.value = value;
  549. return;
  550. }
  551. /*
  552. * 如果当前位置未找到匹配的ThreadLocal,就一直遍历Entry(由于哈希值存在碰撞问题,所以可能初次计算出的哈希值没法用)
  553. * 向后遍历的过程中,会出现以下情形:
  554. * 1. 找到了匹配的ThreadLocal,那么执行上面的if语句,并退出
  555. * 2. 遇到了一个垃圾值
  556. */
  557. if (k == null) {
  558. /*
  559. * 继续从索引index开始遍历map,给ThreadLocal对象安排合适的位置
  560. * 安排完ThreadLocal对象后,还会清理一部分垃圾
  561. */
  562. replaceStaleEntry(key, value, index);
  563. return;
  564. }
  565. }
  566. // 直到遇见了空槽也没找到匹配的ThreadLocal对象,那么在此空槽处安排ThreadLocal对象和缓存的value
  567. tab[index] = new Entry(key, value);
  568. int sz = ++size;
  569. // 从下标i开始向后遍历,清理一部分垃圾值,清理过后元素依然是紧凑的
  570. boolean isRemoved = cleanSomeSlots(index, sz);
  571. // 如果没有元素被清理,那么就要检查当前元素数量是否超过了容量阙值,以便决定是否扩容
  572. if(!isRemoved && sz >= threshold) {
  573. // 需要扩容,扩容的过程也是对所有的key重新哈希的过程
  574. rehash();
  575. }
  576. }
  577. /**
  578. * Remove the entry for key.
  579. */
  580. // 从map中清理key关联的键值对
  581. private void remove(ThreadLocal<?> key) {
  582. Entry[] tab = table;
  583. int len = tab.length;
  584. int i = key.threadLocalHashCode & (len-1);
  585. for (Entry e = tab[i];
  586. e != null;
  587. e = tab[i = nextIndex(i, len)]) {
  588. if (e.get() == key) {
  589. e.clear();
  590. // 从索引i开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑
  591. expungeStaleEntry(i);
  592. return;
  593. }
  594. }
  595. }
  596. /**
  597. * Replace a stale entry encountered during a set operation
  598. * with an entry for the specified key. The value passed in
  599. * the value parameter is stored in the entry, whether or not
  600. * an entry already exists for the specified key.
  601. *
  602. * As a side effect, this method expunges all stale entries in the
  603. * "run" containing the stale entry. (A run is a sequence of entries
  604. * between two null slots.)
  605. *
  606. * @param key the key
  607. * @param value the value to be associated with key
  608. * @param staleSlot index of the first stale entry encountered while
  609. * searching for key.
  610. */
  611. /*
  612. * 从索引staleSlot开始遍历map,给ThreadLocal对象安排合适的位置
  613. * 安排完ThreadLocal对象后,还会清理一部分垃圾
  614. *
  615. * key代表待匹配的ThreadLocal对象,value就是键值对里的值
  616. * staleSlot是遍历连续的元素去匹配ThreadLocal对象的过程中遇到的第一个垃圾值
  617. */
  618. private void replaceStaleEntry(ThreadLocal<?> key, Object value,
  619. int staleSlot) {
  620. Entry[] tab = table;
  621. int len = tab.length;
  622. Entry e;
  623. // Back up to check for prior stale entry in current run.
  624. // We clean out whole runs at a time to avoid continual
  625. // incremental rehashing due to garbage collector freeing
  626. // up refs in bunches (i.e., whenever the collector runs).
  627. int slotToExpunge = staleSlot;
  628. // 从staleSlot开始往前遍历一段连续的元素,找出最早出现垃圾值的位置
  629. for (int i = prevIndex(staleSlot, len);
  630. (e = tab[i]) != null;
  631. i = prevIndex(i, len))
  632. // 遇到了垃圾值
  633. if (e.get() == null)
  634. // slotToExpunge用来记录在索引staleSlot之前的那段连续的元素中最早出现的垃圾值的下标
  635. slotToExpunge = i;
  636. // Find either the key or trailing null slot of run, whichever
  637. // occurs first
  638. /*
  639. * 至此,i指向了一个空槽
  640. * 如果slotToExpunge == staleSlot,说明在(i, staleSlot)这段没有垃圾值
  641. * 如果slotToExpunge != staleSlot,说明在(i, staleSlot)这段有垃圾值,且从i开始遇到的第一个垃圾值是slotToExpunge
  642. *
  643. * 注:在此要想象一个循环链表,(i, staleSlot)只代表一段区域,i和staleSlot的值谁大谁小并不确定
  644. */
  645. // 从staleSlot开始向后遍历一段连续的元素,找出最晚出现垃圾值的位置
  646. for (int i = nextIndex(staleSlot, len);
  647. (e = tab[i]) != null;
  648. i = nextIndex(i, len)) {
  649. ThreadLocal<?> k = e.get();
  650. // If we find key, then we need to swap it
  651. // with the stale entry to maintain hash table order.
  652. // The newly stale slot, or any other stale slot
  653. // encountered above it, can then be sent to expungeStaleEntry
  654. // to remove or rehash all of the other entries in run.
  655. // 找到了匹配的ThreadLocal对象
  656. if (k == key) {
  657. // 直接设置值
  658. e.value = value;
  659. /*
  660. * 将ThreadLocal对象尽量往前挪,已知离理想位置最近且安全的“空”位置就是staleSlot
  661. * 与此同时,垃圾值后移,稍后被清理
  662. */
  663. tab[i] = tab[staleSlot];
  664. tab[staleSlot] = e;
  665. // Start expunge at preceding stale entry if it exists
  666. if (slotToExpunge == staleSlot)
  667. // 可能需要更新slotToExpunge的位置(往后设置)
  668. slotToExpunge = i;
  669. // 从索引slotToExpunge开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑,返回值是那个终止遍历过程的空槽下标
  670. int stop = expungeStaleEntry(slotToExpunge);
  671. // 从下标stop开始向后遍历,清理一部分垃圾值
  672. cleanSomeSlots(stop, len);
  673. return;
  674. }
  675. // If we didn't find stale entry on backward scan, the
  676. // first stale entry seen while scanning for key is the
  677. // first still present in the run.
  678. // 发现新的垃圾值,将slotToExpunge设置到靠后一点的位置
  679. if (k == null && slotToExpunge == staleSlot)
  680. slotToExpunge = i;
  681. }
  682. /*
  683. * 至此,j指向了一个空槽
  684. * 如果slotToExpunge == staleSlot,说明在(staleSlot, j)这段没有垃圾值
  685. * 如果slotToExpunge != staleSlot,有两种可能:
  686. * 1.slotToExpunge在staleSlot之前最远的垃圾值处
  687. * 2.slotToExpunge在staleSlot之后最近的垃圾值处
  688. *
  689. * 注1:这里的最远最近都是建立在连续元素的基础上讨论的,连续元素的意思是中间没有空槽(但可能有垃圾值)
  690. *
  691. * 注2:同上,在此也要想象一个循环链表
  692. */
  693. // If key not found, put new entry in stale slot
  694. // 如果没有找到匹配的ThreadLocal对象,就在staleSlot处创建新的节点
  695. tab[staleSlot].value = null; // 释放值的引用
  696. tab[staleSlot] = new Entry(key, value); // 存储键值对
  697. // If there are any other stale entries in run, expunge them
  698. // 清理标记处的垃圾值
  699. if (slotToExpunge != staleSlot) {
  700. // 从索引slotToExpunge开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑,返回值是那个终止遍历过程的空槽下标
  701. int stop = expungeStaleEntry(slotToExpunge);
  702. // 从下标stop开始向后遍历,捎带清理一部分垃圾值,清理过后元素依然是紧凑的
  703. cleanSomeSlots(stop, len);
  704. }
  705. }
  706. /**
  707. * Expunge a stale entry by rehashing any possibly colliding entries
  708. * lying between staleSlot and the next null slot. This also expunges
  709. * any other stale entries encountered before the trailing null. See
  710. * Knuth, Section 6.4
  711. *
  712. * @param staleSlot index of slot known to have null key
  713. * @return the index of the next null slot after staleSlot
  714. * (all between staleSlot and this slot will have been checked
  715. * for expunging).
  716. */
  717. /*
  718. * 从索引staleSlot开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑
  719. * 返回值是那个终止遍历过程的空槽下标
  720. *
  721. * 执行过程:
  722. * 1. 清理staleSlot中的垃圾值
  723. * 2. 遍历staleSlot后面的元素,直到遇见Entry数组中的空槽(即tab[i]==null)才停止。遍历过程中:
  724. * 2.1 清理遇到的垃圾值
  725. * 2.2 遇到“错位”的元素,将其向前放置在离“理想位置”最近的地方
  726. * 换句话说,经过2.2的操作后,从“理想位置”出发查找某个元素,只要该元素是存在的,
  727. * 那么在找到它的过程中,路过的Entry元素是连成一片的。
  728. * 理解这一点很重要,这是理解set方法的基础之一。
  729. */
  730. private int expungeStaleEntry(int staleSlot) {
  731. Entry[] tab = table;
  732. int len = tab.length;
  733. // expunge entry at staleSlot
  734. // 索引staleSlot处本身标识的就是一个垃圾值,所以需要首先清理掉
  735. tab[staleSlot].value = null;
  736. tab[staleSlot] = null;
  737. // size减1,置空后table的被使用量减1
  738. size--;
  739. // Rehash until we encounter null
  740. Entry e;
  741. int i;
  742. // 继续往后遍历连续的Entry数组,直到遇见一个空槽后停止遍历
  743. for (i = nextIndex(staleSlot, len);
  744. (e = tab[i]) != null;
  745. i = nextIndex(i, len)) {
  746. ThreadLocal<?> k = e.get();
  747. // 如果当前Entry已经不包含ThreadLocal,说明这是个垃圾值,需要清理
  748. if (k == null) {
  749. e.value = null;
  750. tab[i] = null;
  751. size--;
  752. } else {
  753. // 该ThreadLocal对象的“理想位置”
  754. int h = k.threadLocalHashCode & (len - 1);
  755. // 遇到“错位”的元素
  756. if (h != i) {
  757. // 将当前位置置空
  758. tab[i] = null;
  759. // Unlike Knuth 6.4 Algorithm R, we must scan until
  760. // null because multiple entries could have been stale.
  761. // 将其向前放置在离“理想位置”最近的地方
  762. while (tab[h] != null)
  763. h = nextIndex(h, len);
  764. // 将该ThreadLocal对象放进去
  765. tab[h] = e;
  766. /* 这一堆操作目的是让元素存储下标更接近其计算出的哈希值 */
  767. }
  768. }
  769. }
  770. return i;
  771. }
  772. /**
  773. * Heuristically scan some cells looking for stale entries.
  774. * This is invoked when either a new element is added, or
  775. * another stale one has been expunged. It performs a
  776. * logarithmic number of scans, as a balance between no
  777. * scanning (fast but retains garbage) and a number of scans
  778. * proportional to number of elements, that would find all
  779. * garbage but would cause some insertions to take O(n) time.
  780. *
  781. * @param i a position known NOT to hold a stale entry. The
  782. * scan starts at the element after i.
  783. *
  784. * @param n scan control: {@code log2(n)} cells are scanned,
  785. * unless a stale entry is found, in which case
  786. * {@code log2(table.length)-1} additional cells are scanned.
  787. * When called from insertions, this parameter is the number
  788. * of elements, but when from replaceStaleEntry, it is the
  789. * table length. (Note: all this could be changed to be either
  790. * more or less aggressive by weighting n instead of just
  791. * using straight log n. But this version is simple, fast, and
  792. * seems to work well.)
  793. *
  794. * @return true if any stale entries have been removed.
  795. */
  796. // 从下标i开始向后遍历,清理一部分垃圾值,清理过后元素依然是紧凑的
  797. private boolean cleanSomeSlots(int i, int n) {
  798. boolean removed = false;
  799. ThreadLocal.ThreadLocalMap.Entry[] tab = table;
  800. int len = tab.length;
  801. do {
  802. i = nextIndex(i, len);
  803. ThreadLocal.ThreadLocalMap.Entry e = tab[i];
  804. // 遇到了垃圾值
  805. if (e != null && e.get() == null) {
  806. n = len;
  807. removed = true;
  808. // 从索引i开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑,返回值是那个终止遍历过程的空槽下标
  809. i = expungeStaleEntry(i);
  810. }
  811. /*
  812. * 执行log2n次循环
  813. *
  814. * 关于这个扫描次数控制:
  815. * 1. 如果扫描过程中没有遇到垃圾值,那么扫描log2n个元素就结束了,不往下找了
  816. * 2. 只要途中遇到某个垃圾值,扫描次数和范围就会扩大,其中:
  817. * n=len扩大了扫描次数,expungeStaleEntry()方法扩大了扫描范围
  818. */
  819. } while ( (n >>>= 1) != 0);
  820. return removed;
  821. }
  822. /**
  823. * Re-pack and/or re-size the table. First scan the entire
  824. * table removing stale entries. If this doesn't sufficiently
  825. * shrink the size of the table, double the table size.
  826. */
  827. // 扩容并再哈希
  828. private void rehash() {
  829. // 再次清理表中所有垃圾值
  830. expungeStaleEntries();
  831. // Use lower threshold for doubling to avoid hysteresis
  832. /**
  833. * threshold = 2/3 * len
  834. * 所以threshold - threshold / 4 = 1en/2
  835. * 这里主要是因为上面做了一次全清理所以size减小,需要进行判断。
  836. * 判断的时候把阈值调低了。
  837. */
  838. if (size >= threshold - threshold / 4)
  839. // 迫不得已,必须扩容
  840. resize();
  841. }
  842. /**
  843. * Double the capacity of the table.
  844. */
  845. // 扩容,扩大为原来的2倍(这样保证了长度为2的冥)
  846. private void resize() {
  847. Entry[] oldTab = table;
  848. int oldLen = oldTab.length;
  849. int newLen = oldLen * 2;
  850. Entry[] newTab = new Entry[newLen];
  851. int count = 0;
  852. for (int j = 0; j < oldLen; ++j) {
  853. Entry e = oldTab[j];
  854. if (e != null) {
  855. ThreadLocal<?> k = e.get();
  856. // 仍然有垃圾值,则标记清理该元素的引用,以便GC回收
  857. if (k == null) {
  858. e.value = null; // Help the GC
  859. } else {
  860. // 计算新的“理想位置”
  861. int h = k.threadLocalHashCode & (newLen - 1);
  862. // 如果发生冲突,使用线性探测往后寻找合适的位置
  863. while (newTab[h] != null)
  864. h = nextIndex(h, newLen);
  865. newTab[h] = e;
  866. count++;
  867. }
  868. }
  869. }
  870. // 设置新的容量阙值
  871. setThreshold(newLen);
  872. size = count;
  873. table = newTab;
  874. }
  875. /**
  876. * Expunge all stale entries in the table.
  877. */
  878. // 清理表中所有垃圾值
  879. private void expungeStaleEntries() {
  880. Entry[] tab = table;
  881. int len = tab.length;
  882. for (int j = 0; j < len; j++) {
  883. Entry e = tab[j];
  884. // 遇到了垃圾值
  885. if (e != null && e.get() == null)
  886. // 从索引j开始,遍历一段【连续】的元素,清理其中的垃圾值,并使各元素排序更紧凑
  887. expungeStaleEntry(j);
  888. }
  889. }
  890. }
  891. }