Android Handler机制——ThreadLocal
一、构造及初始化
public ThreadLocal() {
}
ThreadLocal本身并不存储主要信息,这从它的构造函数就可看出大概,其并没有强耦合其他类,它主要的作用是提供相关静态方法。但ThreadLocal有个内部类ThreadLocalMap,其中有个数组用于存储相关对象(本质是一个hashmap),而ThreadLocalMap则被存储与Thread对象中。
类关系图如下:
二、get/set
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();
}
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;
}
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 getMap(Thread t) {
return t.threadLocals;
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
ThreadLocal通过get、set来获取、设置存储与ThreadLocalMap中的值,但是ThreadLocalMap并不存储与ThreadLocal,而是存放在Thread中。ThreadLocalMap实例化的地点有点特殊,在set或者get时发现Thread中没有实例化的ThreadLocalMap,会调用createMap来实例化ThreadLocalMap并将其传入对应的Thread中。
值得注意的是,在ThreadLocalMap的getEntry和set方法中都需要传入一个ThreadLocal,没错,ThreadLocalMap将ThreadLocal作为键值,更准确的说,是将ThreadLocal的hash值作为索引,ThreadLocal值本身作为键值。
三、ThreadLocal.ThreadLocalMap
1.构造
如上所述,ThreadLocalMap才是真正存储内容的地方。每一个线程类都可以存储一个ThreadLocalMap,而ThreadLocalMap则可以根据不同的ThreadLocal键值存储不同的值,Looper只是其中之一。
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
从其构造可以看出,ThreadLocalMap的存储介质table是一个数组,ThreadLocal的哈希值经过一定的与运算作为该数组的索引。
类关系图如下:
2.get/set
ThreadLocalMap的存储介质本质上是一个HashMap。
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);
}
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;
}
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;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
从上可看出其get/set原理,当table出现hash值冲突时,存储索引则会往后顺延。而判断key值是否相同,则是通过Entry来实现,Entry继承于弱引用,会保存ThreadLocal,通过比较ThreadLocal,可以判断存储键值是否相同,根据比较结果决定下一步是替换value还是新建Entry。
3.resize
table[]的初始大小为16,当存储内容大于16时。会调用rehash()和resize()方法扩大数组大小。
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
四、总结
以上,是Handler机制中Looper的存储机制。到目前为止,ThreadLocal相关的整体uml图如下: