什么是内存泄漏
简单来讲,就是程序不可能使用的对象或者变量还继续留在内存中,GC回收不掉(吃白饭的,占着茅坑不拉屎)
为什么说ThreadLocal存在内存泄漏
ThreadLocal 是基于 ThreadLocalMap 实现的,ThreadLocalMap 中的key是用WeakReference来封装的是弱引用,意思就是如果GC回收的时候很可能会把key清理掉,但是 Value 由于线程还在存活,所以 Value 一直不会被回收,最后就会发生内存泄漏
public class ThreadLocal<T> {
//省略...
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.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
}
}
小tips:ThreadLocal是通过ThreadLocalMap来实现线程间的隔离的,key就是Threadlocal本身