美文网首页
解读ThreadLocal

解读ThreadLocal

作者: sonnyching | 来源:发表于2017-12-10 23:56 被阅读0次

    1 什么是ThreadLocal

    ThreadLocal,翻译过来,就是"线程本地变量",它是从JDK1.2开始提供的一个类,它能够为不同的线程提供单独的变量副本,使得当在不同的线程调用变量的时候互不干扰。

    从名字可以得到两个关键信息,

    线程——该对象是被线程所持有的;

    本地变量——这个变量作用域在线程内;

    2 ThreadLocal给够给我们带来什么

    1. 解决多线程下的资源竞争问题;
    2. 全局共享变量;

    2.1 解决多线程下的资源竞争问题

    假如有一个动物园,猴子那个扎堆啊 = = , 管理员那个扎心啊 T_T。开始的时候,整个猴子园就一只碗,每次猴子要吃香蕉的时候就在碗里放一只香蕉。碗就相当于向园长(操作系统)申请的空间,就只有一个啦,每只猴子(线程)应该都有自己的一根香蕉(变量)。

    如果照正常情况下,管理员要避免猴子们争夺食物,会让猴子们排队,一只猴子一只猴子的喂,每次往碗里放一根香蕉。排一长队,猴子当然痛恨要抗议啊,因为有些猴子吃得慢,后面的猴子猴孙就等不住了。管理员也要耗费相当的时间,管理员也郁闷。

    于是,管理员干脆向园长申请了又一批碗,干脆一个猴子一只碗算了。这时候,一只猴子一只碗,互不干扰,喂猴子的时间节约了不少。

    ThreadLocal就是这么一个情况,为每一个线程都创建一个线程本地的变量来存储数据,当线程需要使用的时候直接取出来用就可以了。而不必担心变量被其他的线程所篡改。

    2.2 共享变量

    这个也很好理解。给每个猴子分配一只碗以后,猴子要怎么使用这个碗,完全由他自己决定,有碗,真的可以玩所欲为的,他想什么时候用他就什么时候用,碗里的香蕉他想什么时候吃他就什么时候吃。

    与之类似,线程中一旦存了具体的数据,只要在线程内部,什么时候取出来都可以。有时候参数传递不是最佳的解决方案,那么就设置一个全局变量吧,比如在View层设置一个变量,然后在Service层再取出来用。是不是有点像缓存呢?

    2.3 如何使用

    如这个例子所示:

        private static void testThreaLoacl(){
    
            final ThreadLocal<String> tl = new ThreadLocal<String>();
    
            String threadName = Thread.currentThread().getName();
            tl.set(threadName);
    
            new Thread(){
                @Override
                public void run() {
                    System.out.println("---------start");
                    String name = tl.get();
                    System.out.println(name);
                    System.out.println("---------end");
    
                }
            }.start();
    
            String name = tl.get();
            System.out.println(name);
    
        }
    

    运行结果:

    ---------start
    null
    ---------start
    main
    
    • 先new出一个ThreadLocal对象,然后直接set进去value,然后在想要使用的地方使用就可以了;
    • 因为变量是线程内部独享的。当在main线程set的时候,在子线程中是无法获取到main线程set的值的。

    3 经典使用场景

    很多框架汇总都可以看到ThreadLocal的影子。

    ​ 1.Spring中的事务控制。大致的流程是

    向数据库获取一个Connnection,然后存到ThreadLocal中去,然后调用业务方法,最后再从ThreadLocal中取出Connnection,commit!

    ​ 2.playFrameWork1.0中的请求参数。

    可能很多宝宝都不知道PlayFrameWork!,它是一个java的全栈式框架啦,然后略略略(讲不完)….在它的1.0版本中,请求参数在整个MVC三层都可以轻松取得,如,Params.params,原因只是因为它从一开始就将请求参数存到ThreadLocal里面去了。

    4 使用ThreadLocal需要注意什么

    1. ThreadLocal并不能保证数据是安全的。而且,看一下源码就可以发现。

          /**
           * 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 {
              static class Entry extends WeakReference<ThreadLocal> {
                  /** The value associated with this ThreadLocal. */
                  Object value;
                  Entry(ThreadLocal k, Object v) {
                      super(k);
                      value = v;
                  }
              }
      
      

      ThreadLocal内部使用到了一个ThreadLocalMap,具体的数据就是存在里面的Entry,而这个Entry是被定义为WeakReference弱引用的,注释也说明了:为了避免变量的生命周期太长,所以采用弱引用,来确保在特定情况下能够释放这部分的空间。

    2. 容易造成代码耦合。切勿滥用。毕竟每个线程都要为之分配空间,如果把ThreadLocal当缓存使用,迟早要内存溢出的。而且,共享变量的使用是先set,然后再get,如果你的某个方法中在get到这个共享变量,不然就会报错,那你可能无法确保此时这个变量已经被set了,甚至于,前面有人已经set了共享变量,但是你并不知道,为了保险,你又作为一个参数传了进来。

      例1:

          static final ThreadLocal<String> tl = new ThreadLocal<String>();
      
          public void method1() {
              tl.set("哦呼~");
              method2();
          }
          public void method2(){
              System.out.println(tl.get().toString());
          }
      

      可以看到,method1中已经set了变量,然后method2直接从ThreadLocal中获取并使用,如果method1中没有set呢?method2就一定会出现空指针异常。method1根本就不知道调用method2要先set!这种情况下method1和method2之间的耦合度太高了!

      怎么改?就按照正常的写法就好啦。

      例2:

          public void method11(String value) {
              method22(value);
          }
      
          public void method22(String value){
              System.out.println(value.toString());
          }
      

      通过参数传递的参数传递进来就好啦。此时,method11很轻易就知道他需要传参数,那么就会将要打印的参数传进来(这里不考虑传Null)。

    3. 使用ThreadLocal后,当线程复用时可能会带来一些副作用

      看如下代码:

    public static void testThreadLocal2() {
        final ThreadLocal<String> tl = new ThreadLocal<String>();
    
        ExecutorService service = Executors.newFixedThreadPool(1);
    
        service.submit(new Runnable() {
            public void run() {
                tl.set("hello");
            }
        });
    
        service.submit(new Runnable() {
            public void run() {
                String name = tl.get();
                System.out.println(name);
            }
        });
    
        service.shutdown();
    }
    

    运行结果:

    hello
    

    当在一个线程池内部,只有的几个线程的时候,有很大概率会出现线程复用的情况。此时,同一个线程的ThrealLocal是会被窥视到。

    上述代码中,我们以为第一个Runnable任务set的"hello",居然被第二个Runnable任务给get出来了。这不一定是我们预期的。

    就比如,spring中,为了防止请求过多,我们可能会限制线程池的数量。当A用户的请求进来了,使用了a线程,此时a中的ThreadLocal已经被set了value,此时第B用户的请求进来了,假如a线程被复用了,那么B用户中可以直接读到a线程中A用户set下的value。这里的数据就没有被有效隔离开来。是绝对危险的!

    所以,使用了ThreadLocal之后,务必要记得清理ThreadLocal...

    5 源码概览

    1. ThreadLocal的基本组成

      public class ThreadLocal<T> {
          private final int threadLocalHashCode = nextHashCode();
      
       private static AtomicInteger nextHashCode =
              new AtomicInteger();
             
            ...
            
          public T get() {...}
          
          public void set(T value) {...}
          
          public void remove() {...}
          
          ...
          
          static class ThreadLocalMap {
           ...
           Entry(ThreadLocal k, Object v) {
                      super(k);
                      value = v;
               }
               
               ...
               
           static class Entry extends WeakReference<ThreadLocal> {...}
           private Entry[] table;
           ...
          }
      
       ...
      
      }
      
          public class Thread implements Runnable {
           ...
               ThreadLocal.ThreadLocalMap threadLocals = null;
               ...
           }
      
      

      可以看到:

      • 每个Thread中,都有一个变量ThreadLocalMap类型的变量threadLocals,threadLocals用来存放ThreadLocal;
      • ThreadLocalMap中有一个变量叫做table,是一个Entry类型的数组。用于存放不同的ThreadLocal所对应的key。一个Thread可能存在很多ThreadLocal,它们都存在table里面,一个ThreadLocal将会对应一个table的下标;
      • 每个ThreadLocal被初始化的时候,都会先去初始化它内部final类型的threadLocalHashCode。threadLocalHashCode用于确定这个ThreadLocal在Thread中变量Entry数组table的下标。下标的唯一性是通过nextHashCode来确保的,它是一个AtomicInteger类型变量。
    1. get():
      /**
         * 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) {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null)
                map.set(this, value);
            else
                createMap(t, value);
        }
    

    可以看到,set方法中先尝试拿到当前线程的ThreadLocalMap,然后设值。如果没有,创建一个,并设值。

    createMap:

    
        /**
         * Create the map associated with a ThreadLocal. Overridden in
         * InheritableThreadLocal.
         *
         * @param t the current thread
         * @param firstValue value for the initial entry of the map
         * @param map the map to store.
         */
        void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }
    

    创建ThreadLocalMap也很简单,就是new出来,然后将引用交给当前线程持有,这里就可以发现,实际上,ThreadLocal中的数据,其实是保存在当前线程内部的。

    1. get方法:
    /**
         * 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 map = getMap(t);
            if (map != null) {
                ThreadLocalMap.Entry e = map.getEntry(this);
                if (e != null)
                    return (T)e.value;
            }
            return setInitialValue();
        }
    

    通过getMap()拿到当前线程的ThreadLocalMap,然后从table中取出对应的Entry,返回里面的数据即可。

    {
    😔spa太难SEO,我的网站完全木有人🤷‍♀️
    所以不要脸的过来 简书 打广告了...
    
    [sonny的博客](http://chings.cn/article/detail/14)
    
    欢迎光临~~~
    }
    

    sonny的博客

    相关文章

      网友评论

          本文标题:解读ThreadLocal

          本文链接:https://www.haomeiwen.com/subject/bdebixtx.html