带你读《2022技术人的百宝黑皮书》——合理使用线程池以及线程变量(10)https://developer.aliyun.com/article/1340059?groupCode=taobaotech
threadLocal.set()方法
/** *Sets the current thread's copy of this thread-local variable *to the specified value. Most subclasses will have no need to *override this method, relying solely on the {@link #initialValue} *method to set the values of thread-locals. * *@param value the value to be stored in the current thread's copy of * this thread-local. */ public void set(T value) { // 1. 获取当前线程 Thread t = Thread.currentThread(); // 2. 获取当前线程内部的ThreadLocalMap变量ThreadLocalMap map = getMap(t); if (map != null) // 3. 设 置 value map.set(this, value); else // 4. 若map为null则创建ThreadLocalMap createMap(t, value); }
ThreadLocalMap
从JDK源码可见,ThreadLocalMap中的Entry是弱引用类型的,这就意味着如果这个ThreadLocal只被这个 Entry引用,而没有被其他对象强引用时,就会在下一次GC的时候回收掉。
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.
threadLocal.set()方法
10 |
|
*/ |
11 |
|
static class Entry extends WeakReference<ThreadLocal<?>> { |
12 |
|
/** The value associated with this ThreadLocal. */ |
13 |
|
Object value; |
14 |
|
|
15 |
|
Entry(ThreadLocal<?> k, Object v) { |
16 |
|
super(k); |
17 |
|
value = v; |
18 |
|
} |
19 |
|
} |
20 |
|
|
21 |
|
// ... |
22 |
} |
|
带你读《2022技术人的百宝黑皮书》——合理使用线程池以及线程变量(12)https://developer.aliyun.com/article/1340057?groupCode=taobaotech