这里来回答一下前面提到的为什么ThreadLocalMap中将key设计为弱引用,我们假设如果ThreadLocalMap中是强引用会出现什么情况?定义ThreadLocal时定义的强引用被置为null的时候,如果还有其它使用了该ThreadLocal的线程没有完成,还需要很久会执行完成,那么这个线程将一直持有该ThreadLocal实例的引用,直到线程完成,期间ThreadLocal实例都不能被回收,最重要的是如果不了解ThreadLocal内部实现,你可能都不知道还有其他线程引用了threadLocal实例。
线程结束时清除ThreadLocalMap的代码Thread.exit()如下:
/** * This method is called by the system to give a Thread * a chance to clean up before it actually exits. */ private void exit() { if (group != null) { group.threadTerminated(this); group = null; } /* Aggressively null out all reference fields: see bug 4006245 */ target = null; /* Speed the release of some of these resources */ threadLocals = null; inheritableThreadLocals = null; inheritedAccessControlContext = null; blocker = null; uncaughtExceptionHandler = null; } 各线程中threadLocalMap的回收单从引用的角度来看,各线程中的threadLocalMap,其中包括各个Entry的key 和 value,线程(也就是Thread实例)本身一直持有threadLocalMap的强引用,只有在线程结束的时候才会被回收,但是ThreadLocal在实现的时候提供了一些方法:set/get/remove,可以在执行它们的时候回收其它已经失效(key=null)的entry实例。
这里就以set为例看看ThreadLocal是如何回收entry的,ThreadLocal set方法实现如下:
//ThreadLocal public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); // 本次要分析的方法 else createMap(t, value); //这里前面已经分析了 } //ThreadLocalMap private void set(ThreadLocal<?> key, Object value) { // We don't use a fast path as with get() because it is at // least as common to use set() to create new entries as // it is to replace existing ones, in which case, a fast // path would fail more often than not. Entry[] tab = table; int len = tab.length; int i = key.threadLocalHashCode & (len-1); //获取当前threadLocal实例的hashcode,同时也是table的下标 //这里for循环找key,是因为hash冲突会使hashcode指向的下标不是真实的存储位置 for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) { ThreadLocal<?> k = e.get(); //找到了设置为新值 if (k == key) { e.value = value; return; } //entry不为null,key为null //说明原来被赋值过,但是原threadLocal已经被回收 if (k == null) { replaceStaleEntry(key, value, i); return; } } //如果下标对应的entry为null, 则新建一个entry tab[i] = new Entry(key, value); int sz = ++size; //清理threadlocal中其它被回收了的entry(也就是key=null的entry) if (!cleanSomeSlots(i, sz) && sz >= threshold) //rehash rehash(); }看一下cleanSomeSlots的实现:
//ThreadLocalMap private boolean cleanSomeSlots(int i, int n) { boolean removed = false; Entry[] tab = table; int len = tab.length; do { //获取下一个entry的下标 i = nextIndex(i, len); Entry e = tab[i]; //entry不为null,key为null //说明原来被赋值过,但是原threadLocal已经被回收 if (e != null && e.get() == null) { n = len; removed = true; // 删除已经无效的entry i = expungeStaleEntry(i); } } while ( (n >>>= 1) != 0); return removed; } private int expungeStaleEntry(int staleSlot) { Entry[] tab = table; int len = tab.length; // 回收无效entry tab[staleSlot].value = null; tab[staleSlot] = null; size--; // Rehash until we encounter null Entry e; int i; for (i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) { ThreadLocal<?> k = e.get(); //entry不为null,key为null,应该回收 if (k == null) { e.value = null; tab[i] = null; size--; } else { //rehash的实现 //计算当前entry的k的hashcode,看是下标是否应该为i //如果不为i说明,是之前hash冲突放到这儿的,现在需要reash int h = k.threadLocalHashCode & (len - 1); //h!=i 说明hash冲突了, entry不应该放在下标为i的位置 if (h != i) { tab[i] = null; // Unlike Knuth 6.4 Algorithm R, we must scan until // null because multiple entries could have been stale. //找正确的位置h,但是还是有可能冲突所以要循环 while (tab[h] != null) h = nextIndex(h, len); tab[h] = e; } } } return i; }从上面的分析我们可以看到把ThreadLocalMap中的key设计为weakReference,也使set方法可以通过key==null && entry != null判断entry是否失效。
总结一下ThreadLocal set方法的实现:
根据threadLocal计算hashcode找到entry[]数组对应位置设置值
遍历数组找到其它失效的(entry不为null,key为null)的entry删除
内存泄露问题ThreadLocal通过巧妙的设计最大程度上减少了内存泄露的可能,但是并没有完全消除。