Android Handler机制——ThreadLocal

本文解析了Android中的ThreadLocal机制,包括其构造、get/set方法、ThreadLocal与ThreadLocalMap的关系,以及如何存储和管理数据在不同线程间的隔离。重点介绍了ThreadLocalMap的哈希存储和线程绑定原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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图如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值