ThreadLocal
在Thread 上保存了一个ThreadLocalMap,以ThreadLocal object 的hash 为key, thread local object 保存的值为value.
Thread.threadLocals ---> ThreadLocalMap<ThreadLocalHash, value>
ThreadLocal.get() ----> cur_thread.threadLocals.get(cur_thrd_local_hash)
ThreadLocal.set() ----> cur_thread.threadLocals.set(cur_thrd_local_hash, value)
ThreadLocal细节
- ThreadLocalMap size 为 2 ^ n. rehash 阈值为2/3, resize 为3/4
- ThreadLocalMap 使用线性探测实现
- Entry 中对于threadlocal 使用弱引用,避免threadlocal 内存泄漏
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
- 当entry 中的threadlocal 变为null时,应当将此entry 回收。会在set/get过程中尝试清除这样的entry (并将这个entry 后面的entry rehash)
网友评论