Android Handler机制1--ThreadLocal

移步Android Handler机制详解

本片文章的主要内容如下:

  • 1、Java中的ThreadLocal
  • 2、 Android中的ThreadLocal
  • 3、Android 面试中的关于ThreadLocal的问题
  • 4、ThreadLocal的总结

Java中的ThreadLocal和Android中的ThreadLocal的源代码是不一样的

  • 注:基于Android 6.0(6.0.1_r10)/API 23 源码

使用

public class ThreadLocalTest {
    private static ThreadLocal<String> sLocal = new ThreadLocal<>();
    private static ThreadLocal<Integer> sLocal2 = new ThreadLocal<>();

    public static void main(String[] args) {
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    String threadName = Thread.currentThread().getName();
                    System.out.println("thread name " + threadName);
                    sLocal.set(threadName);
                    sLocal2.set(Integer.parseInt(threadName) + 10);
                    try {
                        Thread.sleep(500 * Integer.parseInt(threadName));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println("thread name " + threadName + " ---local " + sLocal.get() + " ---local " + sLocal2.get());
                }
            });
            threads.add(thread);
            thread.setName(i + "");
            thread.start();
        }
    }

}

1 Java中的ThreadLocal

1.1 ThreadLocal的前世今生

  • 早在JDK1.2的版本中就提供java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路,并在JDK1.5开始支持泛型。
  • 当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立的改变自己的副本,而不会影响其他线程所对应的副本。
  • 从线程的角度来看,目标变量就像是本地变量,这也是类名中"Local"所要表达的意思。所以,在Java中编写线程局部变量的代码相对来说要"笨拙"一些,因此造成了线程局部变量没有在Java开发者得到很好的普及。

1.2 ThreadLocal类简介

1.2.1 Java源码描述

  • ThreadLocal类用来提供线程内部的局部变量,这种变量在多线程环境下访问(通过get或set方法访问)时能保证各个线程里的变量相对独立于其他线程内的变量。ThreadLocal实例通常来说都是private static 类型,用于关联线程。

  • ThreadLocal设计的初衷:提供线程内部的局部变量,在本地线程内随时随地可取,隔离其他线程。

  • ThreadLocal的作用是提供线程内的局部变量,这种局部变量仅仅在线程的生命周期中起作用,减少同一个线程内多个函数或者组件一些公共变量的传递的复杂度。

1.2.2 ThreadLocal类结构

5713484-d89c4a36ff46b0be.png

ThreadLocal的结构图:


5713484-25b7d58cc48916c7.png

1.2.3 ThreadLocal常用的方法

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

代码流程很清晰:

  • 先拿到保存键值对的ThreadLocalMap对象实例map,如果map为空(即第一次调用的时候map值为null),则去创建一个ThreadLocalMap对象并赋值给map,并把键值对保存在map
  • 我们看到首先是拿到当前先线程实例t,任何将t作为参数构造ThreadLocalMap对象,为什么需要通过Threadl来获取ThreadLocalMap对象?
//ThreadLocal.java
    /**
     * 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;
    }
  • 我们看到getMap实现非常直接,就是直接返回Thread对象的threadLocal字段。Thread类中的ThreadLocalMap字段声明如下:
//Thread.java
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

我们总结一下:

  • ThreadLocal的set(T) 方法中,首先是拿到当前线程Thread对象中的ThreadLocalMap对象实例threadLocals,然后再将需要保存的值保存到threadLocals里面。
  • 每个线程引用的ThreadLocal副本值都是保存在当前Thread对象里面的。存储结构为ThreadLocalMap类型,ThreadLocalMap保存的类型为ThreadLocal,值为副本值

1.2.3.2 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();
    }
  • 同样的道理,拿到当前线程Thread对象实例中保存的ThreadLocalMap对象map,然后从map中读取键为this(即ThreadLocal类实例)对应的值。
  • 如果map不是null,直接从map里面读取就好了,如果map==null,那么我们需要对当前线程Thread对象实例中保存ThreadLocalMap对象new一下。即通过setInitialValue()方法来创建,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;
    }

代码很清晰,通过createMap来创建ThreadLocalMap对象,前面set(T)方法里面的ThreadLocalMap也是通过createMap来的,我们看看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);
    }

1.2.3.3

remove()方法

         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
  • 直接将当前线程局部变量的值删除,目的是为了减少内存的占用,该方法是JDK1.5新增的方法。
  • 需要指出的,当线程结束以后,对该应线程的局部变量将自动被垃圾回收,所以显示调用该方法清除线程的局部变量并不是必须的操作,但是它可以加速内存回收的数据。

1.3 内部类ThreadLocalMap

/**
     * 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 {}
  • ThreadLocalMap是一个适用于维护线程本地值的自定义哈希映射(hash map),没有任何操作可以让它超出ThreadLocal这个类的范围。
  • 该类是私有的,允许在Thread类中声明字段。为了更好的帮助处理常使用的,hash表条目使用了WeakReferences的键。但是,由于不使用引用队列,所以,只有在表空间不足的情况下,才会保留已经删除的条目

1.3.1 存储结构

  • 通过注释我们知道ThreadLocalMap中存储的是ThreadLocalMap.Entry(后面用Entry代替)对象。
  • 在ThreadLocalMap中管理的也就是Entry对象。
  • 首先ThreadlocalMap需要一个"容器"来存储这些Entry对象,ThreadLocalMap中定义了额Entry数据实例table,用于存储Entry
/**
         * The table, resized as necessary.
         * table.length MUST always be a power of two.
         */
        private Entry[] table;
  • ThreadLocalMap维护一张哈希表(一个数组),表里存储Entry。既然是哈希表,那肯定会涉及到加载因子,即当表里面存储的对象达到容量的多少百分比的时候需要扩容。
  • ThreadLocalMap中定义了threshold属性,当表里存储的对象数量超过了threshold就会扩容。
/**
 * The next size value at which to resize.
 */
private int threshold; // Default to 0

/**
 * Set the resize threshold to maintain at worst a 2/3 load factor.
 */
private void setThreshold(int len) {
    threshold = len * 2 / 3;
}

从上面代码可以看出,加载因子设置为2/3。即每次容量超过设定的len2/3时,需要扩容。

1.3.2 存储Entry对象

  • hash散列的数据在存储过程中可能会发生碰撞,大家知道HashMap存储的是一个Entry链,当hash发生冲突后,将新的的Entry存放在链表的最前端。但是ThreadLocalMap不一样,采用的是*index+1作为重散列的hash值写入
  • 另外有一点需要注意key出现null的原因由于Entry的key是继承了弱引用,在下一次GC是不管它有没有被引用都会被回收
  • 当出现null时,会调用replaceStaleEntry()方法循环寻找相同的key,如果存在,直接替换旧值。如果不存在,则在当前位置上重新创新的Entry。
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

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

看下代码:

/**
         * 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;
                }
                //和HashMap不一样,因为Entry key 继承了所引用,所以会出现key是null的情况!所以会接着在replaceStaleEntry()重新循环寻找相同的key
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }


       /**
         * Increment i modulo len.
         */
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }
  • 通过key(ThreadLocal类型)的hashcode来计算存储的索引位置 i 。
  • 如果 i 位置已经存储了对象,那么就向后挪一个位置以此类推,直到找到空的位置,再讲对象存放。
  • 在最后还需要判断一下当前的存储的对象个数是否已经超出了反之(threshold的值)大小,如果超出了,需要重新扩充并将所有的对象重新计算位置(rehash函数来实现)。

1.3.2.1 rehash()方法

/**
         * Re-pack and/or re-size the table. First scan the entire
         * table removing stale entries. If this doesn't sufficiently
         * shrink the size of the table, double the table size.
         */
        private void rehash() {
            expungeStaleEntries();

            // Use lower threshold for doubling to avoid hysteresis
            if (size >= threshold - threshold / 4)
                resize();
        }
  • rehash函数里面先是调用了expungeStaleEntries()函数,然后再判断当前存储对象的小时是否超出了阀值的3/4。如果超出了,再扩容。

  • ThreadLocalMap里面存储的Entry对象本质上是一个WeakReference<ThreadLcoal>。也就是说,ThreadLocalMap里面存储的对象本质是一个队ThreadLocal的弱引用,该ThreadLocal随时可能会被回收!即导致ThreadLocalMap里面对应的 value的Key是null。我们需要把这样的Entry清除掉,不要让他们占坑。

  • expungeStaleEntries函数就是做这样的清理工作,清理完后,实际存储的对象数量自然会减少,这也不难理解后面的判断的约束条件为阀值的3/4,而不是阀值的大小。

1.3.2.2 expungeStaleEntries()与expungeStaleEntry()方法

/**
         * Expunge all stale entries in the table.
         */
        private void expungeStaleEntries() {
            Entry[] tab = table;
            int len = tab.length;
            for (int j = 0; j < len; j++) {
                Entry e = tab[j];
                if (e != null && e.get() == null)
                    expungeStaleEntry(j);
            }
        }

expungeStaleEntries()方法很简单,主要是遍历table,然后调用expungeStaleEntry(),下面我们来主要讲解下这个函数expungeStaleEntry()函数。

1.3.2.3 expungeStaleEntry()方法

ThreadLocalMap中的expungeStaleEntry(int)方法的可能被调用的处理有:

expungeStaleEntry的调用.png

通过上面的图,不难看出,这个方法在ThreadLocal的set、get、remove时都会被调用

/**
         * Expunge a stale entry by rehashing any possibly colliding entries
         * lying between staleSlot and the next null slot.  This also expunges
         * any other stale entries encountered before the trailing null.  See
         * Knuth, Section 6.4
         *
         * @param staleSlot index of slot known to have null key
         * @return the index of the next null slot after staleSlot
         * (all between staleSlot and this slot will have been checked
         * for expunging).
         */
        private int expungeStaleEntry(int staleSlot) {
            Entry[] tab = table;
            int len = tab.length;

            // expunge entry at staleSlot
            tab[staleSlot].value = null;
            tab[staleSlot] = null;
            size--;

            // Rehash until we encounter null
            Entry e;
            int i;
            for (i = nextIndex(staleSlot, len);
                 (e = tab[i]) != null;
                 i = nextIndex(i, len)) {
                ThreadLocal k = e.get();
                if (k == null) {
                    e.value = null;
                    tab[i] = null;
                    size--;
                } else {
                    int h = k.threadLocalHashCode & (len - 1);
                    if (h != i) {
                        tab[i] = null;

                        // Unlike Knuth 6.4 Algorithm R, we must scan until
                        // null because multiple entries could have been stale.
                        while (tab[h] != null)
                            h = nextIndex(h, len);
                        tab[h] = e;
                    }
                }
            }
            return i;
        }
  • 看出先清理指定的Entry,再遍历,如果发现有Entry的key为null,就清理。
  • Key==null,也就是ThreadLocal对象是null。所以当程序中,将ThreadLocal对象设置为null,在该线程继续执行时,如果执行另一个ThreadLocal时,就会触发该方法。就有可能清理掉Key是null的那个ThreadLocal对应的值。
  • 所以说expungStaleEntry()方法清除线程ThreadLocalMap里面所有key为null的value。

1.3.3 获取Entry对象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
         */
        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);
        }
  • getEntry()方法很简单,直接通过哈希码计算位置 i ,然后把哈希表对应的 i 的位置Entry对象拿出来。
  • 如果对应位置的值为null,这就存在如下几种可能。
  • key 对应的值为null
  • 由于位置冲突,key对应的值存储的位置并不是 i 位置上,即 i 位置上的null并不属于 key 值

因此,需要一个函数去确认key对应的value的值,即getEntryAfterMiss()方法

1.3.3.1 getEntryAfterMiss()函数

/**
         * 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;
        }
  • 第一步,从ThreadLocal的直接索引位置(通过ThreadLocal.threadLocalHashCode&(len-1)运算得到)获取Entry e,如果e不为null,并且key相同则返回e。
  • 第二步,如果e为null或者key不一致则向下一个位置查询,如果下一个位置的key和当前需要查询的key相等,则返回应对应的Entry,否则,如果key值为null,则擦除该位置的Entry,否则继续向一个位置查询。

ThreadLocalMap整个get过程中遇到的key为null的Entry都被会擦除,那么value的上一个引用链就不存在了,自然会被回收。set也有类似的操作。这样在你每次调用ThreadLocal的get方法去获取值或者调用set方法去设置值的时候,都会去做这个操作,防止内存泄露,当然最保险的还是通过手动调用remove方法直接移除

1.3.4 ThreadLocalMap.Entry对象

前面很多地方都在说ThreadLocalMap里面存储的是ThreadLocalMap.Entry对象,那么ThreadLocalMap.Entry独享到底是如何存储键值对的?同时有是如何做到的对ThreadLocal对象进行弱引用?

/**
         * 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;
            }
        }
  • 从源码的继承关系可以看到,Entry是继承WeakReference<ThreadLocal>。即Entry本质上就是WeakReference<ThreadLocal>```
  • Entry就是一个弱引用,具体讲,Entry实例就是对ThreadLocal某个实例的弱引用。只不过,Entry同时还保存了value


    5713484-bc893ac35da6fd7b.png
5713484-fd837cb2b37254f1.png

1.4 总结

  • ThreadLocal是解决线程安全的一个很好的思路,它通过为每个线程提供了一个独立的变量副本解决了额变量并发访问的冲突问题。
  • 在很多情况下,ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。
  • ThreadLocal和synchronize用一句话总结就是一个用存储拷贝进行空间换时间,一个是用锁机制进行时间换空间。
    其实补充知识:
  • ThreadLocal官方建议已定义成private static 的这样让Thread不那么容易被回收
  • 真正涉及共享变量的时候ThreadLocal是解决不了的。它最多是当每个线程都需要这个实例,如一个打开数据库的对象时,保证每个线程拿到一个进而去操作,互不不影响。但是这个对象其实并不是共享的。

4 ThreadLocal会存在内存泄露吗

ThreadLocal实例的弱引用,当前thread被销毁时,ThreadLocal也会随着销毁被GC回收。

参考

Android Handler机制2之ThreadLocal
ThreadLocal

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容