1. main方法中使用
static ThreadLocal<Person> tl = new ThreadLocal<>();
tl.set(new Person());
1.1 set 方法探索
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
- 可以看出底层是一个map, key是当前线程, value是传入进来的对象.
- ThreadLocalMap 是底层 Map的实现.
1.2 ThreadLocalMap 探索
static class ThreadLocalMap {
/**
* 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;
}
}
- 可以看出 ThreadLocalMap 底层使用了 Entry 维护键值对
- Entry 维护的是弱引用对象
- 当强引用对象 t1 被GC时, 这个弱引用对象将会在下一次GC时被直接回收.
2. 主动释放 key.
当 t1 使用完成, 必须显式地移除 map 中的 key, 否则, 当 key=null, 但是 value 却再也无法被访问到且引用存在, 存在内存泄漏.
tl.remove();