ThreadLocal会不会有所谓“内存泄漏”的问题

05-05-09 tyro

关于threadlocal我有一个问题。

一般认为,threadlocal中有一个map,(上文中的private Map storage = Collections.synchronizedMap(new HashMap())),map中的key为Thread.currentThread,我觉得这个map是不是只会增大而不会减小。每多建一个新的线程,就会多一个。而当线程结束时,如果不是线程池的话,线程对象就没用了,但map中没有除去以该线程做key的元素。后果很可能就是,在JVM中有许多线程对象,它们分配的空间无法被收回。

在java sdk api ThreadLocal中有这样一段,是什么意思

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).

         

tyro
2005-05-09 15:17
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了?

banq
2005-05-10 17:41
不会,按照那段英文:after a thread goes away,当一个线程结束,他的引用拷贝将由Thread Local交由垃圾回收机制回收。

tyro
2005-05-11 13:15

after a thread goes away, all of its copies of thread-local instances are subject to garbage collection .

翻译:线程结束后,该线程中所持有的thread-local实例的拷贝交垃圾回收机制处理。

猜你喜欢