关于 ThreadLocal 的疑问
捏造的信仰 2007-02-26 11:21:11 我想知道当线程结束后,相应的 ThreadLocal 对象是否会被释放?我写了一个测试:
import java.util.Date;
/**
* 测试大量 ThreadLocal 是否被释放
*
* @author yidinghe
*/
public class TestLargeAmountThreadLocals extends Thread {
private static ThreadLocal cache = new ThreadLocal();
public void run() {
cache.set(new Date());
}
public static void main(String[] args) throws Exception {
long mem0 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
for (int i = 0; i < 1000; i++) {
new TestLargeAmountThreadLocals().start();
}
Thread.sleep(5000);
long mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("usage: " + (mem1 - mem0));
}
}
测试结果却是:
usage: -17736
我不知道这是怎么回事。