ThreadLocalMap 泄漏demo
时间: 2023-11-08 07:02:46 浏览: 98
ThreadLocalDemo
对于ThreadLocalMap泄露的示例,可以考虑以下代码:
```java
import java.lang.reflect.Field;
public class ThreadLocalLeakDemo {
public static void main(String[] args) throws Exception {
ThreadLocal<Object> threadLocal = new ThreadLocal<>();
// 设置ThreadLocal的值
threadLocal.set(new Object());
// 获取ThreadLocal中的ThreadLocalMap
Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
threadLocalsField.setAccessible(true);
Object threadLocals = threadLocalsField.get(Thread.currentThread());
Class<?> threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
Field tableField = threadLocalMapClass.getDeclaredField("table");
tableField.setAccessible(true);
Object[] table = (Object[]) tableField.get(threadLocals);
// 输出ThreadLocalMap的大小
System.out.println("ThreadLocalMap size: " + (table == null ? 0 : table.length));
// 清空ThreadLocal的值
threadLocal.remove();
// 输出ThreadLocalMap的大小
System.out.println("ThreadLocalMap size after removing the value: " + (table == null ? 0 : table.length));
}
}
```
在上面的示例中,我们使用了Java的反射机制来获取当前线程的ThreadLocalMap并输出其大小。在设置ThreadLocal的值后,我们可以看到ThreadLocalMap的大小为1;在清空ThreadLocal的值后,我们可以看到ThreadLocalMap的大小仍然为1。这就是ThreadLocal泄漏的原因,即使我们在代码中手动删除了ThreadLocal的值,但是对应的Entry在ThreadLocalMap中仍然存在,这就导致了内存泄漏的问题。
阅读全文