ThreadLocal使用分析

前言

  ThreadLocal从名字上直译为本地线程,看上去像是线程的一种子类,如果你这样理解说明你理解错了。

  在上一篇深入理解Android中的消息机制,理解Hander MessageQueue Looper三者之间的关系中提到了ThreadLocal。今天看到一道美团的面试题如何保证一个线程中只有一个Looper。我第一个想到的就是ThreadLocal。因为ThreadLocal可以非常简单的实现保证一个线程中只有一个Looper对象。

ThreadLocal工作原理

   ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,并且在只能在存储改数据的线程中才能获取存储的数据。对于其它线程来说是不可见的,是无法获取到该数据的。为什么ThreadLocal就能实现这样的功能呢?简单的来说就是ThreadLocal为变量在每个不同的线程中创建一个副本,不同线程获取的是每个线程内部的副本。所以就能实现不同线程之间不干扰。

ThreadLocal使用

  说了这么多,还是直接上代码

   public static void main(String[] args) {

        ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
            @Override
            protected Integer initialValue() {
                return -1;
            }
        };
        threadLocal.set(100);
        new Thread() {
            @Override
            public void run() {
                super.run();
                threadLocal.set(80);
                System.out.println(Thread.currentThread().getName() + "   :" + threadLocal.get());
            }
        }.start();
        System.out.println(Thread.currentThread().getName() + "   :" + threadLocal.get());
    }

控制台打印结果:

main   :100
Thread-0   :80

  这里我们看出不同线程中打印的值是不同的,虽然他们访问的是同一个ThreadLocal对象,但是通过ThreadLocal获取的值却是不同的,而且不同线程取出的值都是自己所在线程所设置的值。不同线程之间不互相干扰。接下来我们来揭开ThreadLocal神秘的面纱。

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

  这里我们发现这里是直接从Thread对象中获取ThreadLocalMap对象,说明Thread类中一定有threadLocals这个对象,也就是说不同线程拥有不同的ThreadLocalMap对象。
这里我们先不急着分析ThreadLocalMap这个类,我们先看一下这个Entry这个类。

static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

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

  我们发现Entry类继承自WeakReference并且引用的是ThreadLocal类型,ThreadLocal就是key,这样ThreadLocal与value联系起来了 因为这里ThreadLocal为弱引用类型,一旦ThreadLocal实例为空那么value就会被移除,如果没有其它强引用类型引用它,那么下次垃圾回收的时候将会回收掉这个value对象。

 static class ThreadLocalMap {
        /**
         * The initial capacity -- MUST be a power of two.
         */
        private static final int INITIAL_CAPACITY = 16;

        /**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
        
        /**
         * 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);

            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虽然名字中带着map,但是实际中存储数据是通过数组来实现的。并且数组的初始化容量为16,从ThreadLocalMap的set()方法中我们可以看到ThreadLocalMap存储数据的逻辑如下:

  1. 第一步是通过ThreadLocal的threadLocalHashCode与存储value值的数组长度作&运算生产hash值。这里我们看一下ThreadLocal的threadLocalHashCode源码
  */
    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);
    }

我们可以看到每调用一次nextHashCode()方法就增加HASH_INCREMENT。

  1. 通过key.threadLocalHashCode & (len-1)生成的hash值定位到数组中的i位置,假如i位置存储的value为k,假如k不为空,如果k和当前的ThreadLocal一致,那么替换value值。并且返回
  2. 假如k为空,那么调用replaceStaleEntry(key, value, i)方法,我们看一下replaceStaleEntry(key, value, i)方法的源码
 /**
         * Replace a stale entry encountered during a set operation
         * with an entry for the specified key.  The value passed in
         * the value parameter is stored in the entry, whether or not
         * an entry already exists for the specified key.
         *
         * As a side effect, this method expunges all stale entries in the
         * "run" containing the stale entry.  (A run is a sequence of entries
         * between two null slots.)
         *
         * @param  key the key
         * @param  value the value to be associated with key
         * @param  staleSlot index of the first stale entry encountered while
         *         searching for key.
         */
        private void replaceStaleEntry(ThreadLocal<?> key, Object value,
                                       int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;
            Entry e;

            // Back up to check for prior stale entry in current run.
            // We clean out whole runs at a time to avoid continual
            // incremental rehashing due to garbage collector freeing
            // up refs in bunches (i.e., whenever the collector runs).
            int slotToExpunge = staleSlot;
            for (int i = prevIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = prevIndex(i, len))
                if (e.get() == null)
                    slotToExpunge = i;

            // Find either the key or trailing null slot of run, whichever
            // occurs first
            for (int i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal<?> k = e.get();

                // If we find key, then we need to swap it
                // with the stale entry to maintain hash table order.
                // The newly stale slot, or any other stale slot
                // encountered above it, can then be sent to expungeStaleEntry
                // to remove or rehash all of the other entries in run.
                if (k == key) {
                    e.value = value;

                    tab[i] = tab[staleSlot];
                    tab[staleSlot] = e;

                    // Start expunge at preceding stale entry if it exists
                    if (slotToExpunge == staleSlot)
                        slotToExpunge = i;
                    cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
                    return;
                }

                // If we didn't find stale entry on backward scan, the
                // first stale entry seen while scanning for key is the
                // first still present in the run.
                if (k == null && slotToExpunge == staleSlot)
                    slotToExpunge = i;
            }

            // If key not found, put new entry in stale slot
            tab[staleSlot].value = null;
            tab[staleSlot] = new Entry(key, value);

            // If there are any other stale entries in run, expunge them
            if (slotToExpunge != staleSlot)
                cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
        }

通过这个方法的英文注释我们可以看出这个方法的主要作用就是替换陈旧条目(就是key为null),并且插入新的元素。

  1. 如果没有满足上面两条,那么将会创建一个新的Entry对象,并且放入数组中
分析ThreadLocal的get()方法
 public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

  这里同样获取当前线程的ThreadLocalMap对象,如果不为空,那么把当前ThreadLocal对象作为参数调用ThreadLocalMap的get()方法。如果获取的值不为空,那么返回值,如果为空,就返回初始化initialValue()方法初始化的默认值,所以我们在使用ThreadLocal的时候为了避免出现空指针异常,一定要从写initialValue()方法,返回一个默认值。

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

  和ThreadLocalMap的set()方法类似,先通过与运算获取游标,
如果获取的Entry不为空,并且Entry所引用的和传入的ThreadLocal是同一个对象,那么返回获取的Entry对象。否则将会继续查找。

什么场景下适合使用ThreadLocal呢?

  简单的来说我们需要使用的对象不是线程安全的,但是
对象我们希望他是线程安全的,以线程作为作用域,并且不同的线程具有不同的副本的时候比较适合使用ThreadLocal。很好的例子就是Handler中的Looper对象,对于Handler来说, 需要获取当前线程的Looper对象,而Looper的作用域是线程,不同的线程有着不同的Looper。通过ThreadLocal就可以轻松实现不同的线程中获取不同得Looper对象。