ThreadLocal底层实现原理

一、基础概念

ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量,使线程之间相互独立互不影响

1.1 同步机制的比较


对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式。
前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。

Threadlocal的最大作用就是 代替同步锁,提高相关性能。

与volatile关键字的对比

并发编程中,多个线程访问同一个变量,可能读到另一个线程修改后的值,也可能不是修改后的值。

所以volatile保证我读到的是最新的值,而ThreadLocal保证我读到的是不会被其他线程影响到的值。

1.2 使用场景(多用于全局变量)

1.日志统计:计算接口调用耗时时,缓存当前的开始时间,和请求id

2.读写分离时,缓存读写标志。

3.数据库连接管理


   
   
  1. private static ThreadLocal<Connection> connectionHolder= new ThreadLocal<Connection>() {
  2. public Connection initialValue () {
  3. return DriverManager.getConnection(DB_URL);
  4. }
  5. };
  6. public static Connection getConnection () {
  7. return connectionHolder.get();
  8. }

4.Session管理


   
   
  1. private static final ThreadLocal threadSession = new ThreadLocal();
  2. public static Session getSession () throws InfrastructureException {
  3. Session s = (Session) threadSession.get();
  4. try {
  5. if (s == null) {
  6. s = getSessionFactory().openSession();
  7. threadSession.set(s);
  8. }
  9. } catch (HibernateException ex) {
  10. throw new InfrastructureException(ex);
  11. }
  12. return s;
  13. }

5.调用链(参数传递)

如在公司设置的适配器功能

设置cxGoodsPurchasesFromDubboList


   
   
  1. @Slf4j
  2. @Component
  3. public class CxGoodsPurchasesDtoAdapter implements CxGoodsPurchasesDtoTarget {
  4. private final ThreadLocal<List<CxGoodsPurchasesFromDubbo>> adaptResultContext = new ThreadLocal<>();
  5. @Resource
  6. private CxCommonBO cxCommonBO;
  7. @Resource
  8. private CxMartRService cxMartRService;
  9. private List<CxGoodsPurchasesFromDubbo> cxGoodsPurchasesFromDubboList;
  10. @Override
  11. public void adaptFromDubbo (List<CxGoodsPurchasesInfo> req) {
  12. try {
  13. log.info( "=============start invoke method CxGoodsPurchasesDtoAdapter adaptFromDubbo,param={}", JsonUtils.toJsonTrim(req));
  14. if (CollectionUtils.isEmpty(req)) {
  15. return;
  16. }
  17. cxGoodsPurchasesFromDubboList = new ArrayList<>();
  18. for (CxGoodsPurchasesInfo cxGoodsPurchasesInfo : req) {
  19. CxGoodsPurchasesFromDubbo cxGoodsPurchasesFromDubbo = new CxGoodsPurchasesFromDubbo();
  20. cxGoodsPurchasesFromDubbo.setGoodsCode(cxGoodsPurchasesInfo.getGoodsCode());
  21. cxGoodsPurchasesFromDubbo.setGoodsName(cxGoodsPurchasesInfo.getGoodsName());
  22. cxGoodsPurchasesFromDubbo.setSkuId(cxGoodsPurchasesInfo.getSkuId());
  23. cxGoodsPurchasesFromDubbo.setBarCode(cxGoodsPurchasesInfo.getBarCode());
  24. cxGoodsPurchasesFromDubbo.setBaseUnit(cxGoodsPurchasesInfo.getBaseUnit());
  25. cxGoodsPurchasesFromDubbo.setTaxCode(cxGoodsPurchasesInfo.getTaxCode());
  26. cxGoodsPurchasesFromDubbo.setTaxRatio(cxGoodsPurchasesInfo.getTaxRatio());
  27. cxGoodsPurchasesFromDubbo.setWeight(cxGoodsPurchasesInfo.getWeight());
  28. cxGoodsPurchasesFromDubbo.setWareTypeCode(cxGoodsPurchasesInfo.getWareTypeCode());
  29. cxGoodsPurchasesFromDubbo.setSource(cxGoodsPurchasesInfo.getSource());
  30. cxGoodsPurchasesFromDubbo.setSupplierCode(cxGoodsPurchasesInfo.getSupplierCode());
  31. List<CatFrameworkLevel> catFrameworkLevels = cxGoodsPurchasesInfo.getCatFrameworkLevels();
  32. setCategoryCode(cxGoodsPurchasesFromDubbo, catFrameworkLevels);
  33. setCxGoodsMdl(cxGoodsPurchasesFromDubbo, cxGoodsPurchasesInfo);
  34. cxGoodsPurchasesFromDubboList.add(cxGoodsPurchasesFromDubbo);
  35. }
  36. adaptResultContext.set(cxGoodsPurchasesFromDubboList);
  37. log.info( "adaptResultContext set success,currentThread={}", Thread.currentThread());
  38. } catch (Exception e) {
  39. log.error( "invoke method CxGoodsPurchasesDtoAdapter adaptFromDubbo occur error", e);
  40. }
  41. }

取cxGoodsPurchasesFromDubboList


   
   
  1. @CxRouter
  2. @Slf4j
  3. public class CxGoodsHandler implements Handler {
  4. @Resource
  5. protected CxGoodsRService cxGoodsRService;
  6. @Resource
  7. private CxPurchasesConfigService cxPurchasesConfigService;
  8. @Resource
  9. private CxCommonBO cxCommonBO;
  10. @Resource
  11. private CxGoodsPurchasesDtoAdapter cxGoodsPurchasesDtoAdapter;
  12. @Resource
  13. private CxGoodsFallbackLogsService cxGoodsFallbackLogsService;
  14. @Override
  15. public void handle (List<CxGoodsPurchasesDTO> datas) {
  16. List<CxGoodsPurchasesFromDubbo> cxGoodsPurchasesFromDubboList = cxGoodsPurchasesDtoAdapter.getAdaptResult();
  17. if (CxCollectionUtils.isEmpty(cxGoodsPurchasesFromDubboList)) {
  18. log.info( "cxGoodsPurchasesDtoAdapter getAdaptResult is Empty,start invoke method doInvokeGoodsInterface");
  19. doInvokeGoodsInterface(datas);
  20. return;
  21. }
  22. doSetGoodsFromDubbo(datas, cxGoodsPurchasesFromDubboList);
  23. log.info( "=============after invoke method CxGoodsHandler handle,result={}", JsonUtils.toJsonTrim(datas));
  24. }

二、底层原理分析

2.1 java.lang.Thread#threadLocals属性

每一个Thread 对象均含有一个ThreadLocalMap 类型的成员变量threadLocals ,它存储本线程中所有ThreadLocal对象及其对应的值。

Thread类有一个核心属性threadLocals,这个threadLocals就是用来存储当前线程变量和对应副本值的映射关系的。即让threadLocals引用指向key为threadLocal,value为当前线程的值。

其中键值为当前ThreadLocal变量(该变量与当前线程有关但不是当前线程值),value为变量副本(即T类型的变量的值)。源码如下:


   
   
  1. /* ThreadLocal values pertaining to this thread. This map is maintained
  2.      * by the ThreadLocal class. */
  3.     ThreadLocal. ThreadLocalMap threadLocals = null;

注意:是Thread类有一个threadLocals变量,而不是ThreadLocal类有threadLocals变量(之前理解搞反了)

2.2 java.lang.ThreadLocal.ThreadLocalMap


   
   
  1. /**
  2. * ThreadLocalMap is a customized hash map suitable only for
  3. * maintaining thread local values. No operations are exported
  4. * outside of the ThreadLocal class. The class is package private to
  5. * allow declaration of fields in class Thread. To help deal with
  6. * very large and long-lived usages, the hash table entries use
  7. * WeakReferences for keys. However, since reference queues are not
  8. * used, stale entries are guaranteed to be removed only when
  9. * the table starts running out of space.
  10. */
  11. static class ThreadLocalMap {
  12. /**
  13. * The entries in this hash map extend WeakReference, using
  14. * its main ref field as the key (which is always a
  15. * ThreadLocal object). Note that null keys (i.e. entry.get()
  16. * == null) mean that the key is no longer referenced, so the
  17. * entry can be expunged from table. Such entries are referred to
  18. * as "stale entries" in the code that follows.
  19. */
  20. static class Entry extends WeakReference<ThreadLocal<?>> {
  21. /** The value associated with this ThreadLocal. */
  22. Object value;
  23. Entry(ThreadLocal<?> k, Object v) {
  24. super(k);
  25. value = v;
  26. }
  27. }

ThreadLocalMap 由一个个Entry 对象构成。


Entry 继承自WeakReference<ThreadLocal<?>> ,一个Entry 由ThreadLocal 对象和Object 构
成。由此可见, Entry 的key是ThreadLocal对象,并且是一个弱引用。当没指向key的强引用后,该key就会被垃圾收集器回收,而value为变量值。


2.3 ThreadLocal是如何为每个线程创建变量的副本的

初始时,在Thread里面,threadLocals为空,当通过ThreadLocal变量调用get()方法或者set()方法,就会对Thread类中的threadLocals进行初始化,并且以当前ThreadLocal变量为键值,以ThreadLocal要保存的副本变量为value,存到threadLocals。

然后在当前线程里面,如果要使用副本变量,就可以通过get方法在threadLocals里面查找。

注意:

1.在进行get之前,必须先set,否则会报空指针异常;如果想在get之前不需要调用set就能正常访问的话,必须重写initialValue()方法。

2.3.1 set方法

当执行set方法时,ThreadLocal首先会获取当前线程对象,然后获取当前线程的ThreadLocalMap类型对象。再以当前ThreadLocal对象为key,将值存储进ThreadLocalMap类型对象中。

set方法主要就是初始化threadLocals,不同的线程会new出不同的ThreadLocalMap


   
   
  1. /**
  2. * Sets the current thread's copy of this thread-local variable
  3. * to the specified value. Most subclasses will have no need to
  4. * override this method, relying solely on the {@link #initialValue}
  5. * method to set the values of thread-locals.
  6. *
  7. * @param value the value to be stored in the current thread's copy of
  8. * this thread-local.
  9. */
  10. public void set (T value) {
  11. Thread t = Thread.currentThread();
  12. ThreadLocalMap map = getMap(t);
  13. if (map != null)
  14. map.set( this, value);
  15. else
  16. createMap(t, value);
  17. }

可以看到,set(T value)方法为每个Thread对象都创建了一个ThreadLocalMap,并且将value放入ThreadLocalMap中,ThreadLocalMap作为Thread对象的成员变量保存。


2.3.2 get()方法源码分析:

get方法执行过程类似。ThreadLocal首先会获取当前线程对象,然后获取当前线程的ThreadLocalMap对象。再以当前ThreadLocal对象为key,获取对应的value。


   
   
  1. /**
  2. * Returns the value in the current thread's copy of this
  3. * thread-local variable. If the variable has no value for the
  4. * current thread, it is first initialized to the value returned
  5. * by an invocation of the {@link #initialValue} method.
  6. *
  7. * @return the current thread's value of this thread-local
  8. */
  9. public T get () {
  10. Thread t = Thread.currentThread();
  11. ThreadLocalMap map = getMap(t);
  12. if (map != null) {
  13. ThreadLocalMap. Entry e = map.getEntry( this);
  14. if (e != null) {
  15. @SuppressWarnings("unchecked")
  16. T result = (T)e.value;
  17. return result;
  18. }
  19. }
  20. return setInitialValue();
  21. }
  22. /**
  23. * 获取当前ThreadLocalMap
  24. * Get the map associated with a ThreadLocal. Overridden in
  25. * InheritableThreadLocal.
  26. *
  27. * @param t the current thread
  28. * @return the map
  29. */
  30. ThreadLocalMap getMap (Thread t) {
  31. return t.threadLocals;
  32. }
  33. /**
  34. * 初始化threadLocals
  35. * Create the map associated with a ThreadLocal. Overridden in
  36. * InheritableThreadLocal.
  37. *
  38. * @param t the current thread
  39. * @param firstValue value for the initial entry of the map
  40. */
  41. void createMap (Thread t, T firstValue) {
  42. t.threadLocals = new ThreadLocalMap( this, firstValue);
  43. }
  44. /**
  45. * Variant of set() to establish initialValue. Used instead
  46. * of set() in case user has overridden the set() method.
  47. *
  48. * @return the initial value
  49. */
  50. private T setInitialValue () {
  51. T value = initialValue();
  52. Thread t = Thread.currentThread();
  53. ThreadLocalMap map = getMap(t);
  54. if (map != null)
  55. map.set( this, value);
  56. else
  57. createMap(t, value);
  58. return value;
  59. }
  60. /**
  61. * 初始值为空,若想不为空,则需客户端重写
  62. * Returns the current thread's "initial value" for this
  63. * thread-local variable. This method will be invoked the first
  64. * time a thread accesses the variable with the {@link #get}
  65. * method, unless the thread previously invoked the {@link #set}
  66. * method, in which case the {@code initialValue} method will not
  67. * be invoked for the thread. Normally, this method is invoked at
  68. * most once per thread, but it may be invoked again in case of
  69. * subsequent invocations of {@link #remove} followed by {@link #get}.
  70. *
  71. * <p>This implementation simply returns {@code null}; if the
  72. * programmer desires thread-local variables to have an initial
  73. * value other than {@code null}, {@code ThreadLocal} must be
  74. * subclassed, and this method overridden. Typically, an
  75. * anonymous inner class will be used.
  76. *
  77. * @return the initial value for this thread-local
  78. */
  79. protected T initialValue () {
  80. return null;
  81. }

我们发现如果没有先set的话,即在map中查找不到对应的存储,则会通过调用setInitialValue方法返回i,而在setInitialValue方法中,有一个语句是T value = initialValue(),

而默认情况下,initialValue方法返回的是null。

重写逻辑可以参考如下:


   
   
  1. ThreadLocal <Long > longLocal = new ThreadLocal <Long >(){
  2. protected Long initialValue() {
  3. return Thread.currentThread().getId();
  4. };
  5. };
  6. ThreadLocal < String > stringLocal = new ThreadLocal < String >(){;
  7. protected String initialValue() {
  8. return Thread.currentThread().getName();
  9. };
  10. };

2.3.3 ThreadLocal的remove方法


   
   
  1. /**
  2. * Removes the current thread's value for this thread-local
  3. * variable. If this thread-local variable is subsequently
  4. * {@linkplain #get read} by the current thread, its value will be
  5. * reinitialized by invoking its {@link #initialValue} method,
  6. * unless its value is {@linkplain #set set} by the current thread
  7. * in the interim. This may result in multiple invocations of the
  8. * {@code initialValue} method in the current thread.
  9. *
  10. * @since 1.5
  11. */
  12. public void remove () {
  13. ThreadLocalMap m = getMap(Thread.currentThread());
  14. if (m != null)
  15. m.remove( this);
  16. }
  17. /**
  18. * Remove the entry for key.
  19. */
  20. private void remove (ThreadLocal<?> key) {
  21. Entry[] tab = table;
  22. int len = tab.length;
  23. int i = key.threadLocalHashCode & (len- 1);
  24. for ( Entry e = tab[i];
  25. e != null;
  26. e = tab[i = nextIndex(i, len)]) {
  27. if (e.get() == key) {
  28. e.clear();
  29. expungeStaleEntry(i);
  30. return;
  31. }
  32. }
  33. }

ThreadLocal的remove()方法会先将Entry中对key的弱引用断开,设置为null,然后再清除对应的key为null的value。

2.4 ThreadLocal与内存泄漏

2.4.1内存泄漏的原因

ThreadLocalMap使用ThreadLocal的弱引用作为key,如果一个ThreadLocal不存在外部强引用时,Key(ThreadLocal)势必会被GC回收,这样就会导致ThreadLocalMap中key为null, 而value还存在着强引用,只有thead线程退出以后,value的强引用链条才会断掉,但如果当前线程再迟迟不结束的话(如用线程池进行管理的dubbo线程等),这些key为null的Entry的value就会一直存在一条强引用链(红色链条)

下图可以更直接的表示。其中虚线表示弱引用

è¿éåå¾çæè¿°

下图虚线表示弱引用。ThreadLocal对象被GC回收了,那么key变成了null。Map又是通过key拿到的value的对象。

所以,GC在回收了key所占内存后,没法访问到value的值,因为需要通过key才能访问到value对象。另外,如图所示的引用链:CurrentThread -- Map -- Entry -- value ,所以,在当前线程没有被回收的情况下,value所占内存也不会被回收。所以可能会造成了内存溢出。
 

参考:

 1.ThreadLocal内存泄露 ThreadLocal内存泄露_小大宇的博客-CSDN博客_threadlocal 泄露

ThreadLocal原理及内存泄露预防_puppylpg的博客-CSDN博客_threadlocal内存泄漏

ThreadLocal内存溢出问题_幽夜落雨的博客-CSDN博客

2.4.2 如何防止内存泄漏

因为上述的原因,在ThreadLocal这个类的get()、set()、remove()方法,均有实现回收 key 为 null 的 Entry 的 value所占的内存。

所以,为了防止内存泄露(没法访问到的内存),在不会再用ThreadLocal的线程任务末尾,调用一次 上述三个方法的其中一个即可,一般使用remove。
 

思考

1.threadLocal是如何保证线程之间的值,互相独立的?

由于每一条线程均含有各自私有的ThreadLocalMap容器,这些容器相互独立互不影响,因此不会存在线程安全性问题,从而也无需使用同步机制来保证多条线程访问容器的互斥性。

ThreadLocal对象每次调用set方法,都是设置的是当前线程的threadLocals变量的值。

调用get方法时也是获取当前线程的threadLocals变量。

即ThreadLocalMap对象不一样,且在set/get方法时都按照当前线程设置和获取的。比如线程1的threadLocals变量和线程2threadLocals变量肯定是不同的。

2.ThreadLocal是否会造成内存溢出?

我认为很难造成内存溢出,因为ThreadLocalMap中的Entry继承了WeakReferenc。但可能造成内存泄露。

3.如果key 使用强引用会怎样?

当threadLocalMap的key为强引用回收ThreadLocal时,因为ThreadLocalMap还持有ThreadLocal的强引用,如果没有手动删除或线程没有退出(被线程池管理),ThreadLocal不会被回收,那么将一直占用内存,同样可能导致内存泄漏。并且当前线程很有可能取到之前同名线程的值,造成数据紊乱。

所以使用强引用并不会回收掉ThreadLocal的内存,反而会影响线程之间的相互隔离

@see 14.Java并发编程:深入剖析ThreadLocalhttp://www.cnblogs.com/dolphin0520/p/3920407.html

@see ThreadLocal源码解读http://www.cnblogs.com/micrari/p/6790229.html

4.duboo中使用Threadlocal

首先ThreadLocal是跟着线程走的,而不管是dubbo或者其他的rpc框架或者Springmvc都有个特点:使用的是线程池模型,当线程执行任务结束之后会回到线程池,这时如果在回到线程池之前ThreadLocal没有被清理,当下一次请求拿到这个线程的时候还能读取到之前没有被清理的ThreadLocal的数据,这样显然不是我们想要的结果了。

在 Dubbo 中使用 ThreadLocal ,如果采用默认的设置,每次 Dubbo 调用结束,Dubbo 处理响应线程并不会被销毁, 而是归还到线程池中。而从 ThreadLocal 源码可以看出,每次我们设置的值其实会存在位于 Thread 中 ThreadLocalMap 变量中。

这就导致,下次如果 Dubbo 处理响应恰好继续使用到这个线程,该线程就能调用到上次响应中设置在 ThreadLocal 设置的值。这会导致业务上异常。其实并不止在 Dubbo 中,该案例还会发生在 web项目中,只要相关使用线程池的,都有可能发生。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值