首页  >  文章  >  Java  >  Java中ThreadLocal导致内存溢出(Out Of Memory)的原因是什么?

Java中ThreadLocal导致内存溢出(Out Of Memory)的原因是什么?

WBOY
WBOY转载
2023-04-23 23:58:091080浏览

原因分析

ThreadLocal 导致内存 OOM 的原因是什么?

ThreadLocal 底层通过 ThreadLocalMap 存储数据

源码如下: 

Java中ThreadLocal导致内存OOM的原因是什么

  • 当我们使用ThreadLocal.set()时,set的value与key(即业务自己定义的ThreadLocal类)会存储在ThreadLocalMap的Entry[]数组里

源码如下:

Java中ThreadLocal导致内存OOM的原因是什么

  • 其中Entry是实现了一个弱引用WeakReference,Entry的key(即业务方定义的 ThreadLocal类)会被包装成一个弱引用当成Entry的key。Java的弱引用的定义是,当JVM执行垃圾回收扫描的时候,当发现只有弱引用的对象时,会立即回收此对象,这是ThreadLocal当初设计的时候防止内存溢出的一个手段

源码如下: 

Java中ThreadLocal导致内存OOM的原因是什么

虽然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导致内存溢出(Out Of Memory)的原因是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除