400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

ThreadLocal的基本定义是什么

这期内容当中小编将会给大家带来有关ThreadLocal的基本定义是什么,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

成都创新互联从2013年创立,先为内黄等服务建站,内黄等地企业,进行企业商务咨询服务。为内黄企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

基本定义及解读

官方释义: http://docs.oracle.com/javase/8/docs/api/
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

  类ThreadLocal:  
  public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);        if (e != null)            return (T)e.value;
    }    return setInitialValue();
  }  /**
  * ThreadLocalMap is a customized hash map suitable only for
  * maintaining thread local values. No operations are exported
  * outside of the ThreadLocal class. The class is package private to
  * allow declaration of fields in class Thread.  To help deal with
  * very large and long-lived usages, the hash table entries use
  * WeakReferences for keys. However, since reference queues are not
  * used, stale entries are guaranteed to be removed only when
  * the table starts running out of space.
  */
  static class ThreadLocalMap {...}

  类Thread:  /* ThreadLocal values pertaining to this thread. This map is maintained
   * by the ThreadLocal class. */
   ThreadLocal.ThreadLocalMap threadLocals = null;

Thread1 : 
       ThreadLocalMap1 : 
             
             Thread2 :
       ThreadLocalMap2 :             
             

线程池与ThreadLocal变量的初始化

在线程池复用的情况下,若ThreaLocal数据没有被清理掉,会被后面的请求复用然后拿到被你修改过的值!
之前在实现日志上下文LogContext的时候碰到了类似问题:

  1. 请求A进入Controller中, 开启线程A,LogContext中记录了大量的ThreadLocal中间变量值,在请求响应结束后,请求线程A回归线程池;

  2. 请求B进入Controller中,复用线程A,LogContext会在之前变量值的基础上继续添加信息,这样的日志信息成了叠加的了。

不管是基于自己实现的线程池,还是应用服务器(如Tomcat)的线程池,都需要小心这一点!
标准或者规范做法是在线程变量使用完毕之后,或者finally代码块中调用 threadLocalVariable.remove() 移除,以防被其他线程复用。

上述就是小编为大家分享的ThreadLocal的基本定义是什么了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。


本文名称:ThreadLocal的基本定义是什么
本文来源:http://www.bluegullmedia.com/article/gshgjh.html

其他资讯

让你的专属顾问为你服务

0.0354s