jdk源码解析-java中的ThreadLocal类(面试必备)

变体精灵
• 阅读 1882

《jdk源码解析-java中的ThreadLocal类》首发橙寂博客转发请加此提示

jdk源码解析-java中的ThreadLocal类

关于ThreadLocal这个类,应该很多人都使用过。我们可以认为这是一个操作线程间局部对象的工具类。

首先我们看下官方解释


This class provides thread-local variables.  These variables differ from
their normal counterparts in that each thread that accesses one (via its
{@code get} or {@code set} method) has its own, independently initialized
copy of the variable.  {@code 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).

官方的意思大概是:
此类提供线程局部变量。 这些变量不同于
它们的正常对应部分是,每个线程(通过
{@code get}或{@code set}方法)get/set有自己的,线程间互不影响的独立初始化的
变量的副本。 {@code ThreadLocal}实例通常是私有的
希望将状态与线程相关联的类中的静态字段(例如,
用户ID或交易ID)。

为什么我把ThreadLocal作为了一个工具类存在?在我们的使用用我们经常使用getset方法。就能在当前线程下取得或设置一个value。事实上这个对象也并
没有很多骚东西也就是一个入口而已,以及负责维护ThreadThreadLocalMap的一些关系,但是看本文的关键点也是理清ThreadLocalMap,ThreadLocal,Thread,Entry之间的关系。

下面简单看一下ThreadLocal的get与set方法。


/**
   * Sets the current thread's copy of this thread-local variable
   * to the specified value.  Most subclasses will have no need to
   * override this method, relying solely on the {@link #initialValue}
   * method to set the values of thread-locals.
   *
   * @param value the value to be stored in the current thread's copy of
   *        this thread-local.
   */
  public void set(T value) {
       //获取当前线程中ThreadLocalMap对象
      Thread t = Thread.currentThread();
      ThreadLocalMap map = getMap(t);
      if (map != null)
          map.set(this, value);
      else
          //在当前线程下创建一个map并设置value
          createMap(t, value);
  }

/**
 * Returns the value in the current thread's copy of this
 * thread-local variable.  If the variable has no value for the
 * current thread, it is first initialized to the value returned
 * by an invocation of the {@link #initialValue} method.
 *
 * @return the current thread's value of this thread-local
 */
public T get() {
   //获得当前线程
    Thread t = Thread.currentThread();
    //获得当前线程的ThreadLocalMap对象
    ThreadLocalMap map = getMap(t);
    if (map != null) {
       //获取map中的具体存取的数据。通过ThreadLocal对象实例。
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
          //创建一个map设置一个默认值。
       return setInitialValue();
}

由上可以看出
ThreadLocal负责维护ThreadThreadLocalMap的关系ThreadLocal是作为ThreadLocalMap
key存在的负责存取数据的是ThreadLocalMap。具体存取的数据结构
ThreadLocalMap中的Entry类。

ThreadLocalMap

先从数据结构来分析ThreadLocalMap

  • ThreadLocalMapThreadLocal的内置静态类。Thread中内置了一个ThreadLocalMap的属性threadLocals默认是为null的。
  • ThreadLocalMap内置了Entry类。ThreadLocalMap中内置了一个关键属性Entry类型的数组tables。tables是用来存具体数据的。在ThreadLocalMap`中。数组的下标是以

ThreadLocal中的threadLocalHashCode值作为下标的。这里threadLocalHashCode是原子性的

  • Entry类扩展了WeakReference(弱引用)这一点记住要考的(详情看下面代码)。其中只内置了一个Object类型的value属性。
* 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 {

      /**
       * The entries in this hash map extend WeakReference, using
       * its main ref field as the key (which is always a
       * ThreadLocal object).  Note that null keys (i.e. entry.get()
       * == null) mean that the key is no longer referenced, so the
       * entry can be expunged from table.  Such entries are referred to
       * as "stale entries" in the code that follows.
       */
       //继承WeakReference保证了key一定要为ThreadLocal对象,如果ThreadLocal被回收了。ThreadLocalMap也会回收并不会报错。
       //这里建议看一下强引用与弱引用的区别
      static class Entry extends WeakReference<ThreadLocal<?>> {
          /** The value associated with this ThreadLocal. */
          Object value;

          Entry(ThreadLocal<?> k, Object v) {
              super(k);
              value = v;
          }
      }

      /**
       * The initial capacity -- MUST be a power of two.
       */
       //默认数组大写为16扩容建议*2
      private static final int INITIAL_CAPACITY = 16;

      /**
       * The table, resized as necessary.
       * table.length MUST always be a power of two.
       */
       //具体存数据的table
      private Entry[] table;

      /**
       * The number of entries in the table.
       */
       //存取的条目
      private int size = 0;

      /**
       * The next size value at which to resize.
       */
      //下一个要扩容的大小
      private int threshold; // Default to 0
      }

由以上设计我们就能分析出,一个线程能存多个不同ThreadLocal来管理的对象。一个ThreadLocal只能对应一个线程的ThreadLocalMap。由于存取的
数据结构的对应关系是以ThreadLocal的hash值来对应的。所以不同线程间的对象都是独立的。

ThreadLocalMap的几个关键方法解析

  • ThreadLocalMap的getEntry方法

/**
       * 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
       */
       //通过ThreadLocal获得了value的值
       //如果获取不到那么会调转到getEntryAfterMiss这个方法
      private Entry getEntry(ThreadLocal<?> key) {
          int i = key.threadLocalHashCode & (table.length - 1);
          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 Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
          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;
      }

  • ThreadLocalMap的set方法

/**
        * 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.

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

            //循环去查询已经存在的entry
            //如果key相同就替换
            //如果key为null就清空掉
           for (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 Entry(key, value);
           int sz = ++size;
           if (!cleanSomeSlots(i, sz) && sz >= threshold)
               rehash();
       }

  • ThreadLocalMap的remove方法

这个方法使用完get方法后,倘若不在用到要记得使用,在多线程环境下,如果使用完后不remove掉很同意内存溢出。


/**
/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);

//找到key相同然后把value设置为null
for (Entry e = tab[i];
     e != null;
     e = tab[i = nextIndex(i, len)]) {
    if (e.get() == key) {
      //把value清空
        e.clear();
        expungeStaleEntry(i);
        return;
    }
}
}

总结

本文从与ThreadLocal相关的ThreadLocalMap,Thread,Entry等几个类开始分析。从数据结构以及常用api分析得出:具体的数据是存在Thread类中的ThreadLocalMap类型中的
threadLocals中。具体的数据是存在ThreadLocalMapEntry类型中的tables数组中。其中ThreadLocal是作为key而存在。从而达到了ThreadLocal管理多个线程且不互相冲突。

ThreadLocal在spring5.2的版本中是被抛弃了,这个类如果使用不当很容易导致内存溢出。其中就涉及到了为什么说使用完后要主动remove以及entry中为什么会使用弱引用。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Stella981 Stella981
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Easter79 Easter79
3年前
SpringBoot整合Redis乱码原因及解决方案
问题描述:springboot使用springdataredis存储数据时乱码rediskey/value出现\\xAC\\xED\\x00\\x05t\\x00\\x05问题分析:查看RedisTemplate类!(https://oscimg.oschina.net/oscnet/0a85565fa
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这