ThreadLocal 导致内存 OOM 的原因是什么?
ThreadLocal 底层通过 ThreadLocalMap 存储数据
源码如下:
源码如下:
源码如下:
虽然key被包装成了一个弱引用会被垃圾回收机制给回收,但是value在线程(Thread)不死亡时却可能存在一条强引用链.
由于 value
是强引用,只要 Thread
不死亡时,例如线程池,这条强引用链就会存在,那么value
就不会回收,可能造成内存溢出
引用关系如下: Thread ==> ThreadLocalMap ==> Entry ==> value
但是这个消除强引用链的动作是需要业务方在get的情况下触发的,可能业务方并不会get、也可能get是key不为空,并不会触发 expungeStaleEntry 类。所以开发者要养成良好的习惯,记得用完 ThreadLocal
时,调一次ThreadLocal.remove()
方法或者 ThreadLocal.set(null)
public class ThreadLocalTest {
/**
* 未初始化的本地线程变量
*/
private static ThreadLocal<User> userThreadLocal = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
int threadNum = 10;
List<Thread> threadList = Lists.newArrayList();
for (int i = 0; i < threadNum; ++i) {
long userId = i;
Thread t = new Thread(() -> {
try {
// 设置变量值
userThreadLocal.set(new User(userId, "lanxing" + userId, "2x"));
// 使用变量
doSomething();
} finally {
// 移除变量
userThreadLocal.remove(); //移除ThreadLocal变量
}
}, "T" + i);
threadList.add(t);
t.start();
}
for (int i = 0; i < threadNum; ++i) {
threadList.get(i).join();
}
}
private static void doSomething() {
log.info("Use ThreadLocal variable :{}", JSON.toJSONString(userThreadLocal.get()));
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
private Long id;
private String name;
private String level;
}
打印结果:
14:30:26.790 [T2] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":2,"level":"2x","name":"lanxing2"}
14:30:26.789 [T5] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":5,"level":"2x","name":"lanxing5"}
14:30:26.792 [T0] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":0,"level":"2x","name":"lanxing0"}
14:30:26.792 [T4] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":4,"level":"2x","name":"lanxing4"}
14:30:26.792 [T8] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":8,"level":"2x","name":"lanxing8"}
14:30:26.791 [T1] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":1,"level":"2x","name":"lanxing1"}
14:30:26.792 [T7] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":7,"level":"2x","name":"lanxing7"}
14:30:26.792 [T6] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":6,"level":"2x","name":"lanxing6"}
14:30:26.791 [T9] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":9,"level":"2x","name":"lanxing9"}
14:30:26.790 [T3] INFO io.zhengsh.order.tool.ThreadLocalTest - Use ThreadLocal variable :{"id":3,"level":"2x","name":"lanxing3"}
到此这篇关于Java中ThreadLocal 导致内存 OOM 的原因分析的文章就介绍到这了,更多相关Java 内存OOM 内容请搜索html5模板网以前的文章希望大家以后多多支持html5模板网!