ThreadLocal详解

一、简介

  JDK5以前就有了ThreadLocal,又叫线程本地变量,提供了get与set等方法,这些方法为每一个使用该变量的线程都存有一份独立的副本,因此get总是返回由当前执行线程在调用set方法时设置的最新值。

二、使用

使用方法比较简单,如下。

 	ThreadLocal<M> threadLocal = new ThreadLocal<>();
 	threadLocal.set(new M());
    threadLocal.get();
    threadLocal.remove();

那么问题来了,什么场景下用 ThreadLocal 比较好呢?

ThreadLocal对象通常用于防止对可变的单例变量或全局变量进行共享,这样维持了线程的封闭性,不用再考虑线程安全问题。项目中,通常搭配Spring的AOP来使用,比如之前写的《Redis实现可重入的分布式锁》,使用ThreadLocal来保存锁的拥有者标记。

三、源码分析

先看Thread类的代码部分

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

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

ThreadLocalMap是Thread的静态内部类,可以看出同一个线程只有持有一个ThreadLocal。但是这里为什么会有两个ThreadLocalMap呢?

通过注释内容可知当我们使用ThreadLocal时用的就是变量threadLocals,inheritableThreadLocals是可继承的ThreadLocal,当我们使用InheritableThreadLocal时,就会使用inheritableThreadLocals来保存父线程的本地变量。详细原理可以查看这篇文章,《ThreadLocal父子线程传递实现方案》。

ThreadLocal的set方法源码如下:

public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
    
    
      ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    
     void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

这里的代码很容易看懂,就是把ThreadLocal自己当key和传进来的value保存到ThreadLocalMap中,如果map没有初始化就new一个。

ThreadLocal的get方法源码如下:

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
        // 重点是这行获取Entry对象
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }
    
      private T setInitialValue() {
      // 这里直接返回的null
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

大致逻辑就是先拿到当前线程的ThreadLocalMap,如果map不是null就取entry的值,否则直接返回null。

通过上面可以分析出,ThreadLocal的get、set方法本质上都是对ThreadLocalMap的操作,所以重点看看这个类的实现。

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.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

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

         // 初始化容量 必须为2的N次方
        private static final int INITIAL_CAPACITY = 16;

         // table数组,它的长度必须一直是2的N次方
        private Entry[] table;

         // table中实体的数量
        private int size = 0;

        /**
         * The next size value at which to resize.
         */
        private int threshold; // Default to 0
        
         ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
         	// 初始化table
            table = new Entry[INITIAL_CAPACITY];
            // 计算索引,这里用二进制与运算代替 %取模,效率更高
            int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
            table[i] = new Entry(firstKey, firstValue);
            size = 1;
            setThreshold(INITIAL_CAPACITY);
        }
        
        ...
    }

ThreadLocalMap是一个自定义的hash map,数据其实都保存在table数组中,内部类Entry是一个弱引用可以防止内存溢出。

重点看看这行代码,int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
ThreadLocal.ThreadLocalMap规定了table的大小必须是2的N次幂,这样就可以用位运算代替数学运算,更加高效。

比方说当前table长度是16,那么16-1=15,也就是二进制的1111。现在有一个数字是23,也就是二进制的00010111。23%16=7,&运算的结果也是7。

firstKey.threadLocalHashCode这个hashcode又是如何计算的呢?

private final int threadLocalHashCode = nextHashCode();

    /**
     * The next hash code to be given out. Updated atomically. Starts at
     * zero.
     */
    private static AtomicInteger nextHashCode =
        new AtomicInteger();

    /**
     * The difference between successively generated hash codes - turns
     * implicit sequential thread-local IDs into near-optimally spread
     * multiplicative hash values for power-of-two-sized tables.
     */
    private static final int HASH_INCREMENT = 0x61c88647;

    /**
     * Returns the next hash code.
     */
    private static int nextHashCode() {
        return nextHashCode.getAndAdd(HASH_INCREMENT);
    }

每次计算ThreadLocal的hashcode都会调用nextHashCode()这个方法,然后利用nextHashCode这个线程安全的原子类来累加0x61c88647,最后得到hashcode。

为什么增量是0x61c88647呢?
0x61c88647是斐波那契散列乘数,它的优点是通过它散列(hash)出来的结果分布会比较均匀,可以很大程度上避免hash冲突,已初始容量16为例,hash并与15位运算计算数组下标结果如下:

 

enter description here
enter description here

 

现在再分析ThreadLocalMap的set()方法:

private void set(ThreadLocal<?> key, Object value) {

            Entry[] tab = table;
            int len = tab.length;
            // 这里就解释了为什么tab.length要是2的N次幂
            int i = key.threadLocalHashCode & (len-1);
            // 遍历tab
            for (Entry e = tab[i];
                 e != null;
                 // 给索引+1继续
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();
                // 判断当前的ThreadLocal和这个位置上的是不是同一个,是的话就覆盖
                if (k == key) {
                    e.value = value;
                    return;
                }
                // 如果当前位置是空的,则直接设置
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
                
            }
            //如果上面没有遍历成功则创建新值	
            tab[i] = new Entry(key, value);
            int sz = ++size;
            //满足条件数组扩容x2
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
        // 将索引的值+1
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

ThreadLocalMap的getEntry方法:

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);
        }
        
        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;
        }
        

ThreadLocal的内存泄漏问题

ThreadLocalMap 中使用的 key 为 ThreadLocal 的弱引用,而 value 是强引用。所以,如果 ThreadLocal 没有被外部强引用的情况下,在垃圾回收的时候会 key 会被清理掉,而 value 不会被清理掉。这样一来,ThreadLocalMap 中就会出现key为null的Entry。假如我们不做任何措施的话,value 永远无法被GC 回收,这个时候就可能会产生内存泄露。ThreadLocalMap实现中已经考虑了这种情况,在调用 set()、get()、remove() 方法的时候,会清理掉 key 为 null 的记录。使用完 ThreadLocal方法后 最好手动调用remove()方法

总结:

  1. 每次set的时候往线程里面的ThreadLocal.ThreadLocalMap中的table数组某一个位置塞一个值,这个位置由ThreadLocal中的threadLocaltHashCode取模得到,如果位置上有数据了,就往后找一个没有数据的位置。
  2. 每次get的时候也一样,根据ThreadLocal中的threadLocalHashCode取模,取得线程中的ThreadLocal.ThreadLocalMap中的table的一个位置,看一下有没有数据,没有就往下一个位置找。
  3. 对于某一ThreadLocal来讲,它的索引值i是确定的,在不同线程之间访问时访问的是不同的table数组的同一位置即都为table[i],只不过这个不同线程之间的table是独立的。
  4. 对于同一线程的不同ThreadLocal来讲,这些ThreadLocal实例共享一个table数组,然后每个ThreadLocal实例在table中的索引i是不同的。
  5. 如果想在同一个线程的 ThreadLocal保存不同类型的值,那就需要创建多个ThreadLocal。
  6. ThreadLocal和Synchronized都是为了解决多线程中相同变量的访问冲突问题,不同的是ThreadLocal是典型的空间换时间。
posted @ 2019-10-03 23:19  烟味i  阅读(313)  评论(0编辑  收藏  举报