美文网首页
Android ThreadLocal 的作用和实现原理

Android ThreadLocal 的作用和实现原理

作者: wuchao226 | 来源:发表于2018-07-23 15:35 被阅读22次

    ThreadLocal 的介绍

    ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储以后,只有在指定线程中可以获取到存储的数据,对于其他线程来说无法获取到数据。Looper、ActivityThread 以及 AMS 中都用到了 ThreadLocal。

    使用场景

    1. 当某些数据是以线程为作用域并且不同线程具有不同的数据副本的时候,就可以采用 ThreadLocal。比如对于 Handler 来说,它需要获取当前线程的 Looper,很显然 Looper 的作用域就是线程并且不同线程具有不同的 Looper,这个时候通过 ThreadLocal 就可以轻松实现 Looper 在线程中的存取。
    2. 复杂逻辑下的对象传递,比如监听器的传递,有些时候一个线程中的任务过于复杂,这可能表现为函数调用栈比较深以及代码入口的多样性,在这种情况下,我们又需要监听器能够贯穿整个线程的执行过程,这时可以采用 ThreadLocal,采用 ThreadLocal 可以让监听器作为线程内的全局对象而存在,在线程内部只要通过 get 方法就可以获取到监听器。

    使用方法及原理

    下面通过例子来说明,首先定义一个 ThreadLocal 对象,选择 Boolean 类型,如下所示

    private ThreadLocal<Boolean> mThreadLocal = new ThreadLocal<>();
    

    然后分别在主线程、子线程1和子线程2中设置和访问它的值

    private void threadLocal() {
            mThreadLocal.set(true);
            Log.d(TAG, "[Thread#main]threadLocal=" + mThreadLocal.get());
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    mThreadLocal.set(false);
                    Log.d(TAG, "[Thread#1]threadLocal=" + mThreadLocal.get());
                }
            }.start();
    
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    Log.d(TAG, "[Thread#2]threadLocal=" + mThreadLocal.get());
                }
            }.start();
        }
    

    日志如下


    ThreadLocal.png

    从上面的日志可以看出,虽然在不同的线程中访问的是同一个 ThreadLocal 对象,但是通过 ThreadLocal 获取到的值是不一样的。ThreadLocal 之所以有这样的效果,是因为不同线程访问同一个 ThreadLocal 的 get 方法,ThreadLocal 内部会从各自的线程中取出一个数组,然后在从数组中根据当前 ThreadLocal 的索引去查找出对应的value值,很显然,不同线程中的数组是不同的,这就是为什么通过 ThreadLocal 可以在不同的线程中维护一套数据的副本并且彼此互不干扰。
    ThreadLocal 是一个泛型类型,它的定义为 public class ThreadLocal<T>,只要弄清楚 ThreadLocal 的 get 和 set 方法就可以明白它的工作原理。
    首先看 ThreadLocal 的 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) {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null)
                map.set(this, value);
            else
                createMap(t, value);
        }
    

    在上面的 set 方法中,首先会获取当前线程,通过 getMap(Thread t) 来获取 ThreadLocalMap ,如果这个 map 不为空的话,就将 ThrealLocal 和 我们想存放的 value 设置进去,不然的话就创建一个 ThrealLocalMap 然后再进行设置。

        /**
         * Get the map associated with a ThreadLocal. Overridden in
         * InheritableThreadLocal.
         *
         * @param  t the current thread
         * @return the map
         */
        ThreadLocalMap getMap(Thread t) {
            return t.threadLocals;
        }
    
        /**
         * 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
         */
        void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }
    

    ThreadLocalMap 是 ThreadLocal 里面的静态内部类,而每一个 Thread 都有一个对应的 ThrealLocalMap,在 Thread 类中有一个成员专门用于存储线程的 ThreadLocal 的数据如下所示

    public class Thread implements Runnable {
       /* ThreadLocal values pertaining to this thread. This map is maintained
        * by the ThreadLocal class.
        */
        ThreadLocal.ThreadLocalMap threadLocals = null;
    }
    

    在 threadLocals 内部有一个数组:private Entry[] table,ThreadLocal 的值就是存在这个 table 数组中

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

    下面看 threadLocals 是如何使用 set 方法将 ThreadLocal 的值存储到 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();
            }
    

    上面分析了ThreadLocal的set方法,这里分析下它的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) {
                    @SuppressWarnings("unchecked")
                    T result = (T)e.value;
                    return result;
                }
            }
            return setInitialValue();
        }
    

    可以发现,ThrealLocal 的 get() 方法的逻辑也比较清晰,它同样是取出当前线程的 threadLocals 对象,如果这个对象为 null,就调用 setInitialValue() 方法

        /**
         * Variant of set() to establish initialValue. Used instead
         * of set() in case user has overridden the set() method.
         *
         * @return the initial value
         */
        private T setInitialValue() {
            T value = initialValue();
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null)
                map.set(this, value);
            else
                createMap(t, value);
            return value;
        }
    

    在 setInitialValue() 方法中,将 initialValue() 的值赋给我们想要的值,默认情况下,initialValue() 的值为 null,当然也可以重写这个方法。

    protected T initialValue() {
            return null;
    }
    

    从 ThreadLocal 的 set() 和 get() 方法可以看出,他们所操作的对象都是当前线程的 threalLocals 对象的 table 数组,因此在不同的线程中访问同一个 ThreadLocal 的 set() 和 get() 方法,他们对 ThreadLocal 所做的 读 / 写 操作权限仅限于各自线程的内部,这就是为什么可以在多个线程中互不干扰地存储和修改数据。

    总结

    ThreadLocal 是线程内部的数据存储类,每个线程中都会保存一个ThreadLocal.ThreadLocalMap threadLocals = null;,ThreadLocalMap 是 ThreadLocal 的静态内部类,里面保存了一个 private Entry[] table 数组,这个数组就是用来保存 ThreadLocal 中的值。通过这种方式,就能让我们在多个线程中互不干扰地存储和修改数据。

    相关文章

      网友评论

          本文标题:Android ThreadLocal 的作用和实现原理

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