Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).
我觉得:它好象是说在thread里有一个隐含的对thread-local变量的引用。(在源码中找到以下代码)
Thread.java
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
而在ThreadLocal.java中,有以下
/
* Sets the current thread's copy of this thread-local variable
* to the specified value. Many applications will have no need for
* this functionality, relying solely on the {@link #initialValue()}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current threads' copy of
* this thread-local.
*/
public void set(Object value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t); <--- 这里,等于是说把key-value也放在了当前thread中的thread-local中了
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
综上,是不是其实threadlocal中自己并没有map,而是从调用它的thread中取map?
这样是不是OK了?