功能
用来提供线程内的局部变量,其他线程操作的数据不会对我产生影响。
用法
一般使用ThreadLocal,官方建议我们定义为private public,why? we will talk it later.
public class ThreadLocalDemo {
private static ThreadLocal<String> threadLocal = new ThreadLocal<String>(){
@Override
protected String initialValue() {
return "hello";
}
};
static class MyRunnable implements Runnable{
private int num;
public MyRunnable(int num){
this.num = num;
}
@Override
public void run() {
threadLocal.set(String.valueOf(num));
System.out.println("threadLocalValue:"+threadLocal.get());
}
}
public static void main(String[] args){
new Thread(new MyRunnable(1));
new Thread(new MyRunnable(2));
new Thread(new MyRunnable(3));
}
}
结果如下:
threadLocalValue:2
threadLocalValue:3
threadLocalValue:4
内部实现
先看原理,然后我们再关注一下内存泄露问题。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);//Thread对象和map一一映射,Thread内部维护一个map
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);//map的key为当前的ThreadLocal对象
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
泄露在哪里?
如果我们定义的ThreadLocal是非静态的。
Thread的生命周期是不确定的,也许主线程退出了,而后台子线程还在执行任务。ThreadLocal在子线程结束后被GC回收了,后面子线程用它从map里面取值的时候,key为null,那么value肯定就取不出来了。
内存泄露解决办法:
1.官方建议我们将ThreadLocal定义为static的
2.待续,我参考了一下网上的说法,没搞明白,先研究一下Java的GC回收机制再说.
在Android中应用
最典型的应用当然是Android中的Handler+Looper+MessageQueue模式的应用了。
每一个线程内部都维护一个MessageQueue和一个Looper,线程之间互不影响。
简单看一下Looper的prepare()函数
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");//prepare只能被调用一次
}
sThreadLocal.set(new Looper(quitAllowed));
}
刚开始我们拿到的肯定是null,所以会设置一个轮询器Looper.
public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}
这里的values就相当于map,与当前线程形成映射,每一个线程拿到的是不同的map。然后把我们设置的Looper对象作为value放进去,key值为ThreadLocal对象。
再看看怎么取的。
public T get() {
// Optimized for the fast path.
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);//拿到对应的map
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);
}
几乎跟java中的ThreadLocal一模一样.
当我们保证了Looper在每一个线程中是互不受影响的之后,MessageQueue只需要静静的放在Looper对象内部就可以了.
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}