java.lang.ThreadLocalJava
文章发布较早,内容可能过时,阅读注意甄别。
# 1. 成员变量
AtomicInteger nextHashCode
获得下个hashcode
# 2. 成员函数
get()
从ThreadLocalMap
中取元素ThreadLocalMap.Entry
,ThreadLocalMap
没有元素时,设置初始化值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; }
1
2
3
4
5
6
7
8
9
10remove()
从ThreadLocalMap
中remove(this)
# 3. 内部类
static final class SuppliedThreadLocal<T> extends ThreadLocal<T>
在ThreadLocal默认初始化时使用public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) { return new SuppliedThreadLocal<>(supplier); }
1
2
3
4static class ThreadLocalMap
类用于存储数据,此类中还有静态类static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } }
1
2
3
4
5
6
7
8
9
10