【Android】由Looper引起的ThreadLocal相关分析
什么是Looper
Looper,通过名字也可以知道,是一个循环器。
Looper的核心是一个循环方法,不断地从MessageQueue中取出Message交给Handler去进行处理。
我们也都知道,一个线程只能有一个Looper,一个Looper可以对应多个Handler。那这就引出一个问题,Android是依靠什么机制来控制线程和Looper的这种1:1的关系的呢。
如何存储Looper
在没看源码之前,可以合理猜测比如每个Thread有一个私有的Map来进行存储,Key是对应的类,Value是对应的对象,似乎这样也能解决这个问题。
但是翻看源码之后发现,Thread中有对应的Map,不过不是常用的HashMap,而是:
/* ThreadLocal values pertaining to this thread. This map is maintained * by the ThreadLocal class. */ ThreadLocal.ThreadLocalMap threadLocals = null;
这么一个Map。那么这个Map究竟是个什么玩意儿呢,得先从其外部类ThreadLocal开始分析,这就开始了这篇文章的主体,TreadLocal相关分析。
ThreadLocal
/** * This class provides thread-local variables. These variables differ from * their normal counterparts in that each thread that accesses one (via its * {@code get} or {@code set} method) has its own, independently initialized * copy of the variable. {@code ThreadLocal} instances are typically private * static fields in classes that wish to associate state with a thread (e.g., * a user ID or Transaction ID). * * For example, the class below generates unique identifiers local to each * thread. * A thread's id is assigned the first time it invokes {@code ThreadId.get()} * and remains unchanged on subsequent calls. *
* import java.util.concurrent.atomic.AtomicInteger; * * public class ThreadId { * // Atomic integer containing the next thread ID to be assigned * private static final AtomicInteger nextId = new AtomicInteger(0); * * // Thread local variable containing each thread's ID * private static final ThreadLocal<Integer> threadId = * new ThreadLocal<Integer>() { * @Override protected Integer initialValue() { * return nextId.getAndIncrement(); * } * }; * * // Returns the current thread's unique ID, assigning it if necessary * public static int get() { * return threadId.get(); * } * } *
* Each thread holds an implicit reference to its copy of a thread-local * variable as long as the thread is alive and the {@code ThreadLocal} * instance is accessible; after a thread goes away, all of its copies of * thread-local instances are subject to garbage collection (unless other * references to these copies exist). * * @author Josh Bloch and Doug Lea * @since 1.2 */
遇事不决看一下注释是什么,我就翻译一下第一段。
这个类提供线程本地的变量。这些变量与正常变量不同,因为每个线程都是通过get和set方法访问各个线程自己的、独立的变量副本。这些实例通常希望是与线程相关联的私有静态字段(例如用户ID或者交易ID)。
知道了ThreadLocal的设计目的,接下来看一下对应的get和set方法的具体实现。
set(T value)
/** * 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); }
通过Thread的静态方法拿到了当前线程,然后通过当前线程拿到对应的map,也就是上文提到的ThreadLocal.ThreadLocalMap threadLocals。之后就是包了一下ThreadLocalMap的set方法,注意一下对应的Key和Value,value没什么好说的,Key的值是this。也就是说一定能在利用ThreadLocal进行线程私有变量存储的地方找到对应的ThreadLocal的初始化。
如果对应ThreadLocalMap为空的话就还要进行一个初始化,这里就是懒汉模式了。
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(); }
get方法就是利用了this去获得ThreadLocalMap.Entry然后再去拿到对应的Value值。看过HashMap源码的同学肯定对Entry这个内部类的作用很熟悉,但是这里的Entry有一些特别。
/** * 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; } }
使用的是弱引用,防止前文提到的ThreadLocal对象导致的内存泄露。
MainLooper初始化分析
有了之前讲到的源码,我们分析一下Android中MainLooper的初始化过程。
首先需要知道每一个Java程序都有一个main方法作为程序入口,Android的APP也不例外,这个方法入口在ActivityThread这个类中:
public static void main(String[] args) { ......//在这里进行了MainLooper的初始化工作 Looper.prepareMainLooper();...... }
具体在main方法中做了什么不是这篇博客关注的,代码中有一行Looper.prepareMainLooper();也就是在这里进行了MainLooper的初始化工作.
跟着这一行点进去:
/** * Initialize the current thread as a looper, marking it as an * application's main looper. The main looper for your application * is created by the Android environment, so you should never need * to call this function yourself. See also: {@link #prepare()} */ public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } }
看到了一个熟悉的prepare方法,进行过Android并发开发的小伙伴肯定对这个方法有印象的,使用Handler必须要先调用Looper.prepare()再调用Looper.loop()。那么我们可以看看prepare方法到底做了什么:
/** Initialize the current thread as a looper. * This gives you a chance to create handlers that then reference * this looper, before actually starting the loop. Be sure to call * {@link #loop()} after calling this method, and end it by calling * {@link #quit()}. */ public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); }
看到上文讲到的set方法了吧,在这里创建了线程私有的Looper对象,并且存到了ThreadLocalMap中。
这里出现的ThreadLocal实例为sThreadLocal对象,这个对象是在哪里初始化的呢?
@UnsupportedAppUsage static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
使用的是饿汉模式,在Looper类加载的时候就进行了初始化。
回到ActivityThread的代码中,之后就是再通过get方法拿到这个Looper,然后赋值给sMainLooper。
/** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static @Nullable Looper myLooper() { return sThreadLocal.get(); }
至此,prepareMainLooper方法完成。
总结
整套利用ThreadLocal存储Looper的逻辑总体还是比较清晰的,但还是有一个我自认为比较迷惑人的地方。
就是Thread只持有ThreadLocalMap实例,每个Thread对应一个ThreadLocalMap,而不是ThreadLocal。
也就是可以理解成ThreadLocal的目的是保存类信息,ThreadLocalMap才是真正存储线程的静态私有变量的容器。
也就是这么一个对应关系Thread:ThreadLocalMap == 1:1。ThreadLocal可以看做一个全局单例的类信息。
更多相关文章
- android连接远程数据库教程1
- Android进阶练习 - 高效显示Bitmap(管理Bitmap内存)
- Android(安卓)异步消息处理—让你深入理解 Looper、Handler、Mes
- Android(安卓)TextView的drawLeft、drawRight..
- Android笔试面试题二(常考问答)
- Android中的Handler用法
- 10个经典的Android开源项目(线程,网络等学习不错)
- Android异步消息处理机制完全解析
- 安卓unit与instrumentation测试教程