引言
我们知道在android上,主要利用了Handle实现了线程之间的消息通信。在Handle消息机制中有个很重要的类ThreadLocal,理解ThreadLocal有助于我们更深入的理解Handle通信机制。
android上的ThreadLocal跟java jdk上的实现方式有点不一样,但是它们的功能都是一致的,下面我会用android上的ThreadLocal跟大家进行分析。
ThreadLocal是什么?
要了解一个类,那必须先看它的类注释
Implements a thread-local storage, that is, a variable for which each thread has its own value. All threads share the same ThreadLocal object, but each sees a different value when accessing it, and changes made by one thread do not affect the other threads. The implementation supports null values.
根据上面的意思,简单的说ThreadLocal就是一个供线程保存数据的存储类,但是它可以使各个线程保存在同一个ThreadLocal对象里的数据互不干扰,一个线程修改ThreadLocal里的数据并不会影响其他线程所存储的数据。
感觉用文字描述好乏力啊,还是看看下面的小例子吧。
首先我们先实例化一个存储String类型数据的ThreadLocal
ThreadLocal<String> threadLocal = new ThreadLocal<>();
然后再定义两个线程类
class MyThread1 extends Thread {
@Override
public void run() {
threadLocal.set("MyThread1 data");
Log.i(TAG, getName() + " " + threadLocal.get());
}
}
class MyThread2 extends Thread {
@Override
public void run() {
Log.i(TAG, getName() + " " + threadLocal.get());
threadLocal.set("MyThread2 data");
Log.i(TAG, getName() + " " + threadLocal.get());
}
}
然后再启动这两个线程
new MyThread1().start();
Thread.sleep(1000);
new MyThread2().start();
输出结果如下
在上面的例子中两个线程都是使用同一个threadLocal实例,利用ThredLocal的set和get方法对数据进行存储和获取,在MyThread1中存入数据,在MyThread2并没有获取到,而只有在本线程进行存储的数据,才可以在本线程获取,其他线程无法获取,这保证了线程之间存储的数据不会互相干扰,这就是Threadlocal的神奇之处。
为什么ThreadLocal可以为根据不同的线程对数据进行区分呢?接下我们就要为分析下ThreadLocal到底是如何实现的。
ThreadLocal源码分析
ThreadLocal类里面包含了一个静态内部类Values,以及提供了几个公共的方法set、get、remove,我们根据这个几方法进行分析。
构造方法
public ThreadLocal() {}
没和初始化任何东西,很简单的一个无参构造方法。
set方法
set方法可以为当前线程保存一个变量到ThreadLocal中,且这个值可以为null。
ThreadLocal
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
Values values(Thread current) {
return current.localValues;
}
Values initializeValues(Thread current) {
return current.localValues = new Values();
}
set方法中代码首先获取当前线程currentThread ,并传递给values方法,values方法返回了Thread类的一个成员变量localValues。
Thread
public class Thread implements Runnable {
//...
ThreadLocal.Values localValues;
//...
}
因为返回的localValues为null,所以我们对它进行实例化(initializeValues),然后localValues(values)变量通过put方法把值进行存储。
通过上面简单的分析,我们知道每个线程都有一个ThreadLocal.Values类型的成员变量localValues,利用ThreadLocal的set方法进行存储,本质上是把该数据存储到本线程中的localValues变量上,这样就保证了不同线程存储的数据可以互不干扰,因为数据是保存在自己的线程变量中的。
ThreadLocal.Values
localValues类型是ThreadLocal.Values,那它到底是一个怎么样的类呢,我们继续往下探索。
ThreadLocal.Values
static class Values {
private static final int INITIAL_SIZE = 16;
private Object[] table;
private int mask;
private int size;
private int maximumLoad;
//...
Values() {
initializeTable(INITIAL_SIZE);
this.size = 0;
this.tombstones = 0;
}
private void initializeTable(int capacity) {
this.table = new Object[capacity * 2];
this.mask = table.length - 1;
this.clean = 0;
this.maximumLoad = capacity * 2 / 3; // 2/3
}
//...
}
Values是ThreadLocal的静态内部类,被设计用来保存线程变量的容器,它里面有个table数组,在构造方法会为该数组分配空间,而我们要存入的数据就是方在这个数组中的。
通过ThreadLocal的set的分析,知道set最终调用的是ThreadLocal.Values的put方法,如下:
ThreadLocal.Values#put
void put(ThreadLocal<?> key, Object value) {
cleanUp();
// Keep track of first tombstone. That's where we want to go back
// and add an entry if necessary.
int firstTombstone = -1;
for (int index = key.hash & mask;; index = next(index)) {
Object k = table[index];
if (k == key.reference) {
// Replace existing entry.
table[index + 1] = value;
return;
}
if (k == null) {
if (firstTombstone == -1) {
// Fill in null slot.
table[index] = key.reference;
table[index + 1] = value;
size++;
return;
}
// Go back and replace first tombstone.
table[firstTombstone] = key.reference;
table[firstTombstone + 1] = value;
tombstones--;
size++;
return;
}
// Remember first tombstone.
if (firstTombstone == -1 && k == TOMBSTONE) {
firstTombstone = index;
}
}
}
在上面的代码中通过该ThreadLocal对象的hash值来定位相应的的索引,如果该索引的值与key.reference是同一个对象,那么就把value放到table[index + 1]中。
key.referece到底是什么呢,见如下:
ThreadLocal#reference
public class ThreadLocal<T> {
//...
private final Reference<ThreadLocal<T>> reference
= new WeakReference<ThreadLocal<T>>(this);
//...
}
referece其实是ThreadLocal对象本身的弱引用,使用弱引用可以保证ThreadLocal对象可以得到释放,而不会因table数组的持有导致无法释放资源。
继续put方法中的代码,如果table[index]返回的是null,那么我们就把key.reference和value都放入table数组中,这里的算法我不详细讲解,我们只要记住table数组不仅存储了我们要存入的变量,也存储了当前ThreadLocal的弱引用,如果弱引用存储的位置为 table[index],那么变量存储的位置就为table[index + 1]。在这里我也可以知道,如果有个多个ThreadLocal实例在线程中存储数据,那么这些实例的弱引用和数据都会存储在此table数组中,并且这些数据不会相互干扰。
简单的探索完了ThreadLocal.Vaules类后,我们继续探索ThreadLocal.get方法
get方法
get方法可以获取当线程所存储的变量,如果没有则返回null,源码如下:
ThreadLocal#get
public T get() {
// Optimized for the fast path.
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values != null) {
Object[] table = values.table;
int index = hash & values.mask;
if (this.reference == table[index]) {
return (T) table[index + 1];
}
} else {
values = initializeValues(currentThread);
}
return (T) values.getAfterMiss(this);
}
上面的代码 首先去获取当前线程的localValues变量,如果localValues不为空,那么就根据hash值获取当前ThreadLocal对象的索引index,然后返回的table[index + 1]就是我们所存储的值,是不是跟上面分析put中存储的数据的下标index + 1一样?如果返回为null,那么我们实例化一个新的values值,然后执行values的getAfterMiss(this)方法。
Valuse#getAfterMiss
Object getAfterMiss(ThreadLocal<?> key) {
Object[] table = this.table;
int index = key.hash & mask;
// If the first slot is empty, the search is over.
if (table[index] == null) {
Object value = key.initialValue();
// If the table is still the same and the slot is still empty...
if (this.table == table && table[index] == null) {
table[index] = key.reference;
table[index + 1] = value;
size++;
cleanUp();
return value;
}
// The table changed during initialValue().
put(key, value);
return value;
}
//...
}
因为新实例化后的values 中table数组里面并没有数据,所以table[index]为null,然后把value值设置为initialValue(),见如下
ThreadLocal#initialValue
protected T initialValue() {
return null;
}
然后把当前的ThreadLocal弱引用和value(null)值,存入table数组中,并返回value(null)。这也验证了如果没有之前存储变量,get方法返回的默认值为null。
get方法与set方法是相对应的,通过上面的分析我们可以知道get方法其实获取的还是各自线程中的localValues变量中的值,每个线程对应的localValues内容不一样,获取的值当然会不一样。
remove方法
remove方法的作用其实就是移除存储的数据,把table数组中原本存储的数据置为null,具体是实现方法和上面的一致,我这里就不再进行分析了。
总结:
ThreadLocal 的set、get、remove方法都是针对当前线程的localValuse变量中的table数组进行操作的,因此保证了不同线程对一同个ThreadLocal实例进行数据操作的时候不会互相干扰。在Android中有个地方用到了ThreadLocal,那就是Looper,因为Looper的作用域就是线程,每个线程都有各自的Looper,所以系统把这些Looper都通过ThreadLocal进行存储,便于系统的管理和调度,省去了建立全局存储的麻烦。