1、简介

ThreadLocal指的就是线程本地变量。程序会存在线程安全问题,就是同一份资源在同一个时刻会有多个线程进行操作,导致最终结果与预想不一致。

ThreadLocal中每个线程维护自己的一份变量(ThreadLocalMap),这样这个变量就是这个线程私有的,而且其生命周期和这个线程的生命周期等同。

ThreadLocal其实就是封装了线程本地变量的一系列操作合集。也就是Thread对象中的一个局部私有属性ThreadLocal.ThreadLocalMap threadLocals
下面是截取的Thread的部分代码:

  1. public class Thread implements Runnable {
  2. // 与该线程相关的ThreadLocal值,这个map由ThreadLocal类维护
  3. ThreadLocal.ThreadLocalMap threadLocals = null;
  4. }

线程与线程本地变量的关系如下图
image.png

2、简单使用

这个地方就使用官方的例子来说明,代码如下

  1. import java.util.concurrent.atomic.AtomicInteger;
  2. public class ThreadId {
  3. // Atomic integer containing the next thread ID to be assigned
  4. private static final AtomicInteger nextId = new AtomicInteger(0);
  5. // Thread local variable containing each thread's ID
  6. private static final ThreadLocal<Integer> threadId =
  7. new ThreadLocal<Integer>() {
  8. @Override
  9. protected Integer initialValue() {
  10. return nextId.getAndIncrement();
  11. }
  12. };
  13. // Returns the current thread's unique ID, assigning it if necessary
  14. public static int get() {
  15. return threadId.get();
  16. }
  17. }

这段代码主要是给每个线程生成一个唯一标识的id,线程的id,在调用ThreadId.get()方法的手才进行赋值,而且后面的调用将不会改变这个值。

每个线程访问自己的本地变量的时候(通过get或者set方法)都会初始化一个变量副本ThreadLocalMap(如果已经存在则直接使用)。

ThreadLocal实例通常是类中的私有静态字段。目的是将一些状态和线程管理起来。

3、ThreadLocal实现原理

线程本地变量副本的初始化是懒加载的,都是第一次调用get或者set方法的时候才会进行初始化。并且这个副本并不是维护在ThreadLocal中,而是调用线程的一个变量 ThreadLocal.ThreadLocalMap threadLocals = null

3.1 get方法

源码分析:

  1. public T get() {
  2. // 获取当前调用线程
  3. Thread t = Thread.currentThread();
  4. // 获取当前调用线程的threadLocals map引用
  5. ThreadLocalMap map = getMap(t);
  6. if (map != null) {
  7. // 如果map不为空则当前map已经初始化了
  8. // 获取entry
  9. ThreadLocalMap.Entry e = map.getEntry(this);
  10. if (e != null) { // 说明初始化过当前ThreadLocal对象关联的线程局部变量
  11. @SuppressWarnings("unchecked")
  12. T result = (T)e.value;
  13. // 直接拿到值并返回
  14. return result;
  15. }
  16. }
  17. // 如果map为空代表还未初始化,则需要进行初始化
  18. // 当前线程的threadLocals是空
  19. // 当前线程与当前ThreadLocal对象没有生成关联关系
  20. return setInitialValue();
  21. }
  22. // 返回调用线程的threadLocals变量值
  23. ThreadLocalMap getMap(Thread t) {
  24. return t.threadLocals;
  25. }
  26. private T setInitialValue() {
  27. // 获取初始值
  28. T value = initialValue();
  29. // 获取当前调用线程
  30. Thread t = Thread.currentThread();
  31. // 获取当前调用线程的ThreadLocalMap对象
  32. ThreadLocalMap map = getMap(t);
  33. if (map != null) {
  34. // 存在则设置初始化值
  35. map.set(this, value);
  36. } else {
  37. // 给当前调用线程创建ThreadLocalMap对象
  38. createMap(t, value);
  39. }
  40. // 返回本地变量值
  41. return value;
  42. }
  43. // 本地变量初始值
  44. protected T initialValue() {
  45. return null;
  46. }
  47. // 给当前调用线程初始化ThreadLocalMap对象
  48. void createMap(Thread t, T firstValue) {
  49. t.threadLocals = new ThreadLocalMap(this, firstValue);
  50. }

流程图
未命名文件.png

3.2 set方法

set方法主要是修改当前本地变量的值

  1. public void set(T value) {
  2. // 获取当前线程
  3. Thread t = Thread.currentThread();
  4. ThreadLocalMap map = getMap(t);
  5. if (map != null)
  6. // 设置值
  7. map.set(this, value);
  8. else
  9. // 创建map
  10. createMap(t, value);
  11. }
  12. // 给当前调用线程初始化ThreadLocalMap对象
  13. void createMap(Thread t, T firstValue) {
  14. t.threadLocals = new ThreadLocalMap(this, firstValue);
  15. }

流程图
ThreadLocal#set流程图.png

3.3 remove方法

移除当前ThreadLocal对象与当前调用线程相关联的线程局部变量。这个方法本身很简单

  1. public void remove() {
  2. // 获取map
  3. ThreadLocalMap m = getMap(Thread.currentThread());
  4. if (m != null)
  5. // 移除key
  6. m.remove(this);
  7. }

相对来说ThreadLocal本身的方法都比较简单,ThreadLocal的主要难点和功能都在ThreadLocalMap中。比如

3.4 hash相关属性

ThreadLocal主要是操作ThreadLocalMap,ThreadLocalMap是一个hash map,但是没有jdk的HashMap那么复杂。
ThreadLocalMap中的key和value被封装成一个弱引用的Entry对象。key就是ThreadLocal。所以ThreadLocal中一定会绑定一个hashCode。这个地方主要来分析一下这个hashcode

  1. public class ThreadLocal<T> {
  2. // ThreadLocal对象的hashCode
  3. private final int threadLocalHashCode = nextHashCode();
  4. // 下一个hashCode
  5. private static AtomicInteger nextHashCode =
  6. new AtomicInteger();
  7. // hash增长值
  8. // 这是一个斐波拉契数,黄金分割数,使用这个数据累加可以使元素更加的散列,不容易hash冲突
  9. private static final int HASH_INCREMENT = 0x61c88647;
  10. // 下一个hashCode
  11. private static int nextHashCode() {
  12. return nextHashCode.getAndAdd(HASH_INCREMENT);
  13. }
  14. }

从上面的代码可以看出,ThreadLocal对象使用一个原子类来存储下一个唯一的hashCode.并且使用一个斐波拉契作为一个递增数保证数据更加散列。

4、真正的内核ThreadLocalMap

上一节分析了ThreadLocal的主要方法,可以发现其实其使用以及原理非常简单。
但是还有更加深入细致的核心内容没有分析就是ThreadLocalMap这个数据结构。
ThreadLocalMap也是一个Map类型的数据结构。但是它和jdk的HashMap是不一样的,它的操作会相对简单,不需要向HashMap那样通过链表以及红黑树来解决hash冲突,更加没有什么链化和树化操作。ThreadLocalMap实现要相对简单些,也很巧妙,下面开始分析

先上一张核心方法执行图

ThreadLocal图.png

1 Entry分析

首先需要理解一个概念弱引用,直接上代码,解释弱引用:

  1. public class Wref {
  2. public static void main(String[] args) {
  3. // t 是Test的强引用
  4. Test t = new Test();
  5. // weakRef是Test的弱引用
  6. WeakReference<Test> weakRef = new WeakReference<>(t);
  7. System.out.println("弱引用:" + weakRef.get());
  8. // 断开强引用
  9. t = null;
  10. System.out.println("去除强应用,垃圾未回收:" + weakRef.get());
  11. // 手动执行垃圾回收
  12. System.gc();
  13. // 打印垃圾回收后弱引用的值
  14. System.out.println("去除强引用,垃圾已回收:" + weakRef.get());
  15. }
  16. public static class Test{
  17. }
  18. }
  19. // 打印结果
  20. //弱引用:com.cx.ref.Wref$Test@5cad8086
  21. //去除强应用,垃圾未回收:com.cx.ref.Wref$Test@5cad8086
  22. //去除强引用,垃圾已回收:null

所以对于弱引用,只要弱引用对象没有强引用了,下次垃圾回收,这个对象肯定被回收,那么弱引用的对象就会是null。
ThreadLocalMap中的Entry对象就是一个弱应用

  1. static class Entry extends WeakReference<ThreadLocal<?>> {
  2. /** The value associated with this ThreadLocal. */
  3. Object value;
  4. Entry(ThreadLocal<?> k, Object v) {
  5. // ThreadLocal对象为key,那么当ThreadLocal对象没有强引用的时候,等待一次GC后
  6. // Entry对象的key肯定是null
  7. // 这个机制对后面识别无效节点非常有用
  8. super(k);
  9. value = v;
  10. }
  11. }

当ThreadLocal对象没有强引用后,当经过一次垃圾回收后,这个对象会被回收,那么Entry的key就是是null

2 相关属性介绍

  1. static class ThreadLocalMap {
  2. static class Entry extends WeakReference<ThreadLocal<?>> {
  3. /** The value associated with this ThreadLocal. */
  4. Object value;
  5. Entry(ThreadLocal<?> k, Object v) {
  6. super(k);
  7. value = v;
  8. }
  9. }
  10. /**
  11. * The initial capacity -- MUST be a power of two.
  12. * 散列表的初始容量,一定是2的次方数,
  13. * 这样求取桶位 可以使用 hashcode & (len - 1)来求取
  14. */
  15. private static final int INITIAL_CAPACITY = 16;
  16. /**
  17. * The table, resized as necessary.
  18. * table.length MUST always be a power of two
  19. */
  20. // 数组
  21. private Entry[] table;
  22. /**
  23. * The number of entries in the table.
  24. */
  25. // 元素大小
  26. private int size = 0;
  27. /**
  28. * The next size value at which to resize.
  29. */
  30. // 阈值 默认0, 扩容阈值
  31. private int threshold; // Default to 0
  32. /**
  33. * Set the resize threshold to maintain at worst a 2/3 load factor.
  34. */
  35. // 阈值为散列表长度的2/3
  36. private void setThreshold(int len) {
  37. threshold = len * 2 / 3;
  38. }
  39. /**
  40. * Increment i modulo len.
  41. */
  42. // 获取下一个index,
  43. // i + 1 < len就返回 i + 1 否则返回 0
  44. // 从这个地方可以看出,这个数组是存放元素的方式是环状存储,或者说可以环绕式访问
  45. private static int nextIndex(int i, int len) {
  46. return ((i + 1 < len) ? i + 1 : 0);
  47. }
  48. /**
  49. * Decrement i modulo len.
  50. */
  51. // 获取前一个index
  52. // i -1 <= 0 则返回 i -1 否则是 len -1
  53. private static int prevIndex(int i, int len) {
  54. return ((i - 1 >= 0) ? i - 1 : len - 1);
  55. }
  56. }

3 构造方法

  1. ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
  2. // 初始化数组
  3. table = new Entry[INITIAL_CAPACITY];
  4. // 获取桶位
  5. int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
  6. // 存值
  7. table[i] = new Entry(firstKey, firstValue);
  8. // 元素大小
  9. size = 1;
  10. // 设置扩容阈值 16 * 2 / 3 = 10
  11. setThreshold(INITIAL_CAPACITY);
  12. }

这个地方就是ThreadLocal中createMap方法的具体执行。ThreadLocalMap是懒加载的,只有第一次访问的时候才会初始化

4 getEntry方法

ThreadLocal中的get方法就是通过getEntry来获取值的

  1. private Entry getEntry(ThreadLocal<?> key) {
  2. // 获取数组index
  3. int i = key.threadLocalHashCode & (table.length - 1);
  4. Entry e = table[i];
  5. if (e != null && e.get() == key)
  6. // 如果当前桶位有值且key是当前key,则返回
  7. return e;
  8. else
  9. // 数组在i 没有值或者key不一致
  10. return getEntryAfterMiss(key, i, e);
  11. }
  12. // key 当前ThreadLocal对象
  13. // i 数组当前索引
  14. // e 当前处理的Entry
  15. private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
  16. Entry[] tab = table;
  17. int len = tab.length;
  18. while (e != null) {
  19. // 获取当前e的key
  20. ThreadLocal<?> k = e.get();
  21. // 如果k 就是当前的key则直接返回Entry
  22. if (k == key)
  23. return e;
  24. if (k == null)
  25. // 在找到key对应的的Entry之前,已经发现了失效的Entry则需要删除所有的过期Entry
  26. expungeStaleEntry(i);
  27. else
  28. // 如果还不是当前Key则继续往后找
  29. i = nextIndex(i, len);
  30. e = tab[i];
  31. }
  32. // 如果向后查找到最后都没有找到,说明真的没有这个Entry直接返回null
  33. return null;
  34. }

5 expungeStaleEntry(i)方法

获取Entry时,在找到对应key的Entry之前发现了失效的Entry,则需要执行此操作将当前失效节点以及后续失效节点进行删除

  1. // staleSlot过期索引
  2. private int expungeStaleEntry(int staleSlot) {
  3. Entry[] tab = table;
  4. int len = tab.length;
  5. // expunge entry at staleSlot
  6. // 删除插槽中的无效数据
  7. tab[staleSlot].value = null;
  8. tab[staleSlot] = null;
  9. size--;
  10. // Rehash until we encounter null
  11. // 重新hash直到遇到null
  12. Entry e;
  13. int i;
  14. // 从staleSlot的下一个索引开始找:staleSlot + 1
  15. // 直到找到null停止
  16. for (i = nextIndex(staleSlot, len);
  17. (e = tab[i]) != null;
  18. i = nextIndex(i, len)) {
  19. ThreadLocal<?> k = e.get();
  20. if (k == null) {
  21. // 找到失效的Entry然后移除
  22. e.value = null;
  23. tab[i] = null;
  24. size--;
  25. } else { // 如果不是失效的Entry那么重新hash这个Entry的位置
  26. int h = k.threadLocalHashCode & (len - 1);
  27. if (h != i) {
  28. // 如果h != i 代表 之前设置这个Entry的时候存在hash冲突,h这个位置已经有元素了
  29. // 那么需要将当前Entry从i移除,然后再从h这个位置开始往后找,直至找到空桶
  30. // 清空i位置Entry
  31. tab[i] = null;
  32. // Unlike Knuth 6.4 Algorithm R, we must scan until
  33. // null because multiple entries could have been stale.
  34. // 从h开始往查找,找到第一个桶位为null的元素
  35. while (tab[h] != null)
  36. h = nextIndex(h, len);
  37. tab[h] = e;
  38. }
  39. // 如果 h = i说明没有hash冲突,直接放置就可以
  40. }
  41. }
  42. // 返回 最后值为null的索引
  43. return i;
  44. }

6 set方法

ThreadLocal中set方法会使用这个方法

  1. private void set(ThreadLocal<?> key, Object value) {
  2. // We don't use a fast path as with get() because it is at
  3. // least as common to use set() to create new entries as
  4. // it is to replace existing ones, in which case, a fast
  5. // path would fail more often than not.
  6. Entry[] tab = table;
  7. // 数组长度
  8. int len = tab.length;
  9. // 当前key在数组中的位置
  10. int i = key.threadLocalHashCode & (len-1);
  11. // 如果key产生了hash冲突,则执行for循环里面的代码
  12. for (Entry e = tab[i];
  13. e != null;
  14. e = tab[i = nextIndex(i, len)]) {
  15. // 获取当前Entry的key
  16. ThreadLocal<?> k = e.get();
  17. // key相同,说明找到了,直接替换然后结束
  18. if (k == key) {
  19. e.value = value;
  20. return;
  21. }
  22. // k == null 说明数组当前位置元素为过期元素
  23. if (k == null) {
  24. // 替换逻辑,然后直接返回
  25. replaceStaleEntry(key, value, i);
  26. return;
  27. }
  28. }
  29. // 说明key没有产生hash冲突,直接进行设置
  30. tab[i] = new Entry(key, value);
  31. int sz = ++size;
  32. // 判断是否需要进行hash
  33. // 如果清除了一部分slot,那么肯定不需要进行扩容
  34. // 如果没有清除并且数量大于阈值了,那么必须要进行扩容了
  35. if (!cleanSomeSlots(i, sz) && sz >= threshold)
  36. rehash();
  37. }

7 replaceStaleEntry

set方法中,当查找时发现过期key时,可以进行占用

  1. private void replaceStaleEntry(ThreadLocal<?> key, Object value,
  2. int staleSlot) {
  3. Entry[] tab = table;
  4. int len = tab.length;
  5. Entry e;
  6. // Back up to check for prior stale entry in current run.
  7. // We clean out whole runs at a time to avoid continual
  8. // incremental rehashing due to garbage collector freeing
  9. // up refs in bunches (i.e., whenever the collector runs).
  10. // 开始删除的桶位
  11. int slotToExpunge = staleSlot;
  12. // 从staleSlot往前查找 返回null结束,将找到的Entry中key == null的索引赋值给slotToExpunge
  13. for (int i = prevIndex(staleSlot, len);
  14. (e = tab[i]) != null;
  15. i = prevIndex(i, len))
  16. if (e.get() == null)
  17. slotToExpunge = i;
  18. // Find either the key or trailing null slot of run, whichever
  19. // occurs first
  20. // 从staleSlot + 1 开始往后查找,找到null结束
  21. for (int i = nextIndex(staleSlot, len);
  22. (e = tab[i]) != null;
  23. i = nextIndex(i, len)) {
  24. ThreadLocal<?> k = e.get();
  25. // If we find key, then we need to swap it
  26. // with the stale entry to maintain hash table order.
  27. // The newly stale slot, or any other stale slot
  28. // encountered above it, can then be sent to expungeStaleEntry
  29. // to remove or rehash all of the other entries in run.
  30. if (k == key) {// 找到key对应的Entry了
  31. // 替换值
  32. e.value = value;
  33. //
  34. tab[i] = tab[staleSlot];
  35. tab[staleSlot] = e;
  36. // Start expunge at preceding stale entry if it exists
  37. if (slotToExpunge == staleSlot)
  38. // 如果找到key了,并且staleSlot前面没有失效的entry,并且再找到key之前也没有
  39. // 失效的entry,那么就从当前找到key这个桶位开始往后进行探测删除
  40. slotToExpunge = i;
  41. cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
  42. return;
  43. }
  44. // If we didn't find stale entry on backward scan, the
  45. // first stale entry seen while scanning for key is the
  46. // first still present in the run.
  47. if (k == null && slotToExpunge == staleSlot)
  48. // staleSlot是肯定会被替换的
  49. // 如果staleSlot前面没有找到失效的entry,那么如果在staleSlot后面发现的第一个就是
  50. // 后面开始删除的开始桶位
  51. slotToExpunge = i;
  52. }
  53. // If key not found, put new entry in stale slot
  54. // 向后查找过程中没有找到对应的key,将新的Entry放在失效的桶位
  55. tab[staleSlot].value = null;
  56. tab[staleSlot] = new Entry(key, value);
  57. // If there are any other stale entries in run, expunge them
  58. if (slotToExpunge != staleSlot)
  59. // 不相等说明staleSlot前面有过期数据或者后面又过期数据
  60. cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
  61. }

这个地方解释下slotToExpunge的作用,就是记录这一段连续桶位最前面的那个失效的索引值
如果这个索引值存在则从这个索引值往后面进行失效数据清理

8 cleanSomeSlots

一般只有删除一个无效数据或者新增一个数据的时候才会执行这个清理

  1. // i 是expungeStaleEntry清理完成后返回的最后一个桶位为null的索引
  2. // n 初始值table.length,
  3. private boolean cleanSomeSlots(int i, int n) {
  4. // 是否清楚数据标志
  5. boolean removed = false;
  6. Entry[] tab = table;
  7. int len = tab.length;
  8. do {
  9. i = nextIndex(i, len);
  10. Entry e = tab[i];
  11. if (e != null && e.get() == null) {
  12. // 过期key
  13. n = len;
  14. removed = true;
  15. // 清理过期数据
  16. i = expungeStaleEntry(i);
  17. }
  18. //
  19. } while ( (n >>>= 1) != 0);
  20. return removed;
  21. }

这个地方的n会有两个取值

  • table.length replaceStaleEntry方法调用
  • size 插入的时候

如果没有发现过期的entry那么最多只会执行log(n)次

9 rehash

这个方法就是用来扩容的。
只有添加数据的时候才会执行,并且需要满则以下条件

  1. cleanSomeSlots 没有清除掉任何过期数据
  2. size >= threshold(数组长度的2/3)

    1. private void rehash() {
    2. // 删除所有过期数据
    3. expungeStaleEntries();
    4. // 如果size > 3/4的阈值了就进行扩容
    5. // Use lower threshold for doubling to avoid hysteresis
    6. if (size >= threshold - threshold / 4)
    7. resize();
    8. }
  3. 首先会清除所有的过期数据

  4. 如果这个时候清除了过期数据,元素数量大于3/4的阈值则必须扩容

10 resize

这个方法特别简单,

  1. 新建一个两倍长度的数组
  2. 将原数组中未过期的数据全部重新计算hash值然后确定位置再重新填充到新的数组中
  3. 设置新的阈值
  4. 设置新的长度
  5. 将旧的数组替换成新的数组

    1. private void resize() {
    2. Entry[] oldTab = table;
    3. int oldLen = oldTab.length;
    4. int newLen = oldLen * 2;
    5. Entry[] newTab = new Entry[newLen];
    6. int count = 0;
    7. for (int j = 0; j < oldLen; ++j) {
    8. Entry e = oldTab[j];
    9. if (e != null) {
    10. ThreadLocal<?> k = e.get();
    11. if (k == null) {
    12. e.value = null; // Help the GC
    13. } else {
    14. int h = k.threadLocalHashCode & (newLen - 1);
    15. while (newTab[h] != null)
    16. h = nextIndex(h, newLen);
    17. newTab[h] = e;
    18. count++;
    19. }
    20. }
    21. }
    22. setThreshold(newLen);
    23. size = count;
    24. table = newTab;
    25. }

    11 remove

    remove方法的逻辑

  6. 根据hash值计算出索引 index

  7. 从索引 index 开始,往后查找知道找到对应的entry,如果没有找到则返回
  8. 如果找到了将entry中的key清除,让后执行过期entry的清理
    1. /**
    2. * Remove the entry for key.
    3. */
    4. private void remove(ThreadLocal<?> key) {
    5. Entry[] tab = table;
    6. int len = tab.length;
    7. int i = key.threadLocalHashCode & (len-1);
    8. for (Entry e = tab[i];
    9. e != null;
    10. e = tab[i = nextIndex(i, len)]) {
    11. if (e.get() == key) {
    12. e.clear();
    13. expungeStaleEntry(i);
    14. return;
    15. }
    16. }
    17. }

5、子线程不可继承性

从代码中可以知道,副本数据是保存在Thread对象中的。所以同一个ThreadLocal变量在父线程中被设置值后,在子线程中是没法获取到的。

6、InheritableThreadLocal

这个类可以解决子线程不能共享父线程ThreadLocal数据的问题
因为在线程new的时候会执行下面这行代码,会将父线程的inheritableThreadLocals给子线程

  1. if (inheritThreadLocals && parent.inheritableThreadLocals != null)
  2. this.inheritableThreadLocals =
  3. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

下面主要看看createInheritedMap
主要是将父线程的ThreadLocalMap传入,让后根据每个entry生成中的key和value生成一个新的Entry

  1. static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
  2. return new ThreadLocalMap(parentMap);
  3. }
  4. private ThreadLocalMap(ThreadLocalMap parentMap) {
  5. Entry[] parentTable = parentMap.table;
  6. int len = parentTable.length;
  7. setThreshold(len);
  8. table = new Entry[len];
  9. for (int j = 0; j < len; j++) {
  10. Entry e = parentTable[j];
  11. if (e != null) {
  12. @SuppressWarnings("unchecked")
  13. ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
  14. if (key != null) {
  15. // 将父线程的值传入子线程让子线程重新初始化值
  16. Object value = key.childValue(e.value);
  17. Entry c = new Entry(key, value);
  18. int h = key.threadLocalHashCode & (len - 1);
  19. while (table[h] != null)
  20. h = nextIndex(h, len);
  21. table[h] = c;
  22. size++;
  23. }
  24. }
  25. }
  26. }
  1. public class InheritableThreadLocal<T> extends ThreadLocal<T> {
  2. // 值初始化
  3. protected T childValue(T parentValue) {
  4. return parentValue;
  5. }
  6. // 获取inheritableThreadLocals
  7. ThreadLocalMap getMap(Thread t) {
  8. return t.inheritableThreadLocals;
  9. }
  10. // 将生成的map挂在到inheritableThreadLocals上
  11. void createMap(Thread t, T firstValue) {
  12. t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
  13. }
  14. }

从代码可以看出,虽然InheritableThreadLocal解决了子线程不能共享父线程的数据问题。但是这个值是线程是咧化的时候赋值上去的。如果是使用线程池,对于已经存在的线程这个就没有效果了

7、ThreadLocal内存泄漏问题

1、一般情况下ThreadLocal对象都是被修饰成static final, 这个也是官方的推荐使用方法,所以ThreadLocal对象基本不会存在过期现象,所以虽然ThreadLocal的方法都回进行过期数据的删除,但是其实并没有过期的数据。所以如果这个线程长期存活,当线程比较多的时候,或者ThreadLocal比较多的时候,这些数据都没法进行删除,那么这些数据将无法进行回收,而造成内存泄漏。所以set或者get之后一定要remove

8、遗留问题

前面说了,对于父子线程,使用InheritableThreadLocal可以解决子线程访问父线程的ThreadLocalMap.但是对于线程池中的已存在线程,这个没法解决。所以这个问题怎么解决呢。使用阿里开源的TransmittableThreadLocal可以解决这个问题。这个在这里不分析了,后面在专门分析