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 源码
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.pngThreadLocal的结构图:
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。
看下代码:
/** * 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
。也就是说,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)方法的可能被调用的处理有:
通过上面的图,不难看出,这个方法 在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 { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal k, Object v) { super(k); value = v; } }
- 从源码的继承关系可以看到,Entry是继承WeakReference
。即Entry本质上就是WeakReference ``` -
Entry就是一个弱引用,具体讲,Entry实例就是对ThreadLocal某个实例的弱引用。只不过,Entry同时还保存了value
5713484-bc893ac35da6fd7b.png
1.4 总结
- ThreadLocal是解决线程安全的一个很好的思路,它通过为每个线程提供了一个独立的变量副本解决了额变量并发访问的冲突问题。
- 在很多情况下,ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。
- ThreadLocal和synchronize用一句话总结就是一个用存储拷贝进行空间换时间,一个是用锁机制进行时间换空间。
其实补充知识: - ThreadLocal官方建议已定义成private static 的这样让Thread不那么容易被回收
- 真正涉及共享变量的时候ThreadLocal是解决不了的。它最多是当每个线程都需要这个实例,如一个打开数据库的对象时,保证每个线程拿到一个进而去操作,互不不影响。但是这个对象其实并不是共享的。
2 Android中的ThreadLocal
2.1 ThreadLocal的作用
- Android中的ThreadLocal和Java 的ThreadLocal是一致的,每个线程都有自己的局部变量,一个线程的本地变量对其他线程是不可见的
- ThreadLocal不是用与解决共享变量的问题,不是为了协调线程同步而存在,而是为了方便每个线程处理自己的状态而引入的一个机制
2.2 ThreadLocal的结构
ThreadLocal的源代码在ThreadLocal.java
5713484-ed7645a01b7d2ab9.png可以直观地看到在android中的ThreadLocal类提供了一些方法和一个静态内部类Value,其中 Values主要是用来保存线程的变量的一个类,它相当于一个容器,存储保存进来的变量。
2.3ThreadLocal的成员变量
/** Weak reference to this thread local instance. */ private final Reference> reference = new WeakReference>(this); /** Hash counter. */ private static AtomicInteger hashCounter = new AtomicInteger(0); /** * Internal hash. We deliberately don't bother with #hashCode(). * Hashes must be even. This ensures that the result of * (hash & (table.length - 1)) points to a key and not a value. * * We increment by Doug Lea's Magic Number(TM) (*2 since keys are in * every other bucket) to help prevent clustering. */ private final int hash = hashCounter.getAndAdd(0x61c88647 * 2);
我们发现成员变量主要有3个,那我们就依次来说下
- reference:通过弱引用存储ThreadLocal本身,主要是防止线程自身所带的数据都无法释放,避免OOM。
- hashCounter:是线程安全的加减操作,getAndSet(int newValue)取当前的值,并设置新的值
- hash:里面的0x61c88647 * 2的作用是:在Value存在数据的主要存储数组table上,而table被设计为下标为0,2,4...2n的位置存放key,而1,3,5...(2n-1)的位置存放的value,0x61c88647*2保证了其二进制最低位为0,也就是在计算key的下标时,一定是偶数位。
2.4 ThreadLocal的方法
ThreadLocal除了构造函数一共6个方法,我们就依次说下
2.4.1 get()方法
该方法返回线程局部变量的当前线程副本中的值
/** * Returns the value of this variable for the current thread. If an entry * doesn't yet exist for this variable on this thread, this method will * create an entry, populating the value with the result of * {@link #initialValue()}. * * @return the current value of the variable for the calling thread. */ @SuppressWarnings("unchecked") public T get() { // Optimized for the fast path. // 获取当前线程 Thread currentThread = Thread.currentThread(); // 获取当前线程的Value 实例 Values values = values(currentThread); if (values != null) { Object[] table = values.table; //如果键值的key的索引为index,则所对应到的value索引为index+1 //所以 hash&value.mask获取就是key的索引值 int index = hash & values.mask; if (this.reference == table[index]) { return (T) table[index + 1]; } } else { // 如果当前Value实例为空,则创建一个Value实例 values = initializeValues(currentThread); } return (T) values.getAfterMiss(this); }
通过代码,我们得出get()是通过value.table这个数据通过索引值来找到值的
2.4.2 initializeValues(currentThread)方法
/** * Creates Values instance for this thread and variable type. */ Values initializeValues(Thread current) { return current.localValues = new Values(); }
通过上面代码我们知道initializeValues(Thread)方法主要是直接new出一个新的Values对象。
2.4.3 initialValue()方法
该方法返回此线程局部变量的当前线程的"初始值"
/** * Provides the initial value of this variable for the current thread. * The default implementation returns {@code null}. * * @return the initial value of the variable. */ protected T initialValue() { return null; }
也就是默认值为Null,当没有设置数据的时候,调用get()的时候,就返回Null,可以在创建ThreadLocal的时候复写initialValue()方法可以定义初始值。
2.4.4 set(T value)
将此线程局部变量的当前线程副本中的值设置为指定值。
/** * Sets the value of this variable for the current thread. If set to * {@code null}, the value will be set to null and the underlying entry will * still be present. * * @param value the new value of the variable for the caller thread. */ public void set(T value) { //获取当前线程 Thread currentThread = Thread.currentThread(); // 获取 当前线程的Value Values values = values(currentThread); if (values == null) { values = initializeValues(currentThread); } // 将数据设置到Value values.put(this, value); }
2.4.5 remove()
/** * Removes the entry for this variable in the current thread. If this call * is followed by a {@link #get()} before a {@link #set}, * {@code #get()} will call {@link #initialValue()} and create a new * entry with the resulting value. * * @since 1.5 */ public void remove() { Thread currentThread = Thread.currentThread(); Values values = values(currentThread); if (values != null) { values.remove(this); } }
2.4.6 values
/** * Gets Values instance for this thread and variable type. */ Values values(Thread current) { return current.localValues; }
通过线程获取Values对象。
写到这里突然发现7.0已经更改 暂不往下继续
问题
1 ThreadLocal主要用途
- ThreadLocal的作用是提供线程内的局部变量,不同的线程之间不会相互干扰,这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或组件之间一些公共变量的传递的复杂度。
- ThreadLocal提供线程内部的局部变量,在本线程内随时随地可取,隔离其他线程。
2 ThreadLocal内部实现原理,怎么保证数据中仅被当前线程持有?
ThreadLocal的值放入了当前线程的一个Values实例中,所以只能在本线程访问,其他线程无法访问。
3 ThreadLocal修饰的变量一定不能被其他线程访问吗?
- 不是,对于子线程是可以访问父线程中的ThreadLocal修饰的变量的。
- 在ThreadLocal中的inheritValues(Values fromParent)方法获取父线程中的值
3 ThreadLocal的对象存放在哪里?
- 是在堆上,在Java中,线程都会有一个栈内存,栈内存属于单个线程,其存储的变量只能在其所属线程中可见。
- ThreadLocal的值是被线程实例所有,而线程是由其创建的类型所持有,所以ThreadLocal实例实际上也是被其他创建的类所持有的,故它们都存在于堆上。
4 ThreadLocal会存在内存泄露吗
ThreadLocal实例的弱引用,当前thread被销毁时,ThreadLocal也会随着销毁被GC回收。
参考
Android Handler机制2之ThreadLocal
ThreadLocal
更多相关文章
- Android(安卓)Handler 消息机制原理解析
- android开发积累4-android使用HttpURLConnection访问网络
- android中Message机制的灵活应用
- android下对xml的解析
- Android(安卓)EditText 共用TextWatcher,在TextWatcher中确定对应
- Intent调用
- Android的“垃圾回收机制”---智能指针(android refbase类(sp wp))
- Android(安卓)时间对象操作工具类
- Android进程和线程