Java 内存泄漏原因(长生命周期的对象持有短生命周期对象的引用、未正确关闭资源等)

Java 内存泄漏原因

  1. 长生命周期的对象持有短生命周期对象的引用:例如,静态集合不断添加对象而不清理
java 复制代码
private static final List<byte[]> cache = new ArrayList<>();

void add() {
    cache.add(new byte[1024 * 1024]);
}
  1. 未正确关闭资源:例如,数据库连接、文件流、网络连接未关闭
java 复制代码
FileInputStream fileInputStream = null;
try {
    fileInputStream = new FileInputStream("target.txt");
} catch (IOException e) {
    e.printStackTrace();
}
  1. 内部类持有外部类引用:非静态内部类持有外部类实例,若内部类生命周期更长,会导致外部类无法释放
java 复制代码
public class Outer {
    private String value = "Outer";

    class Inner {
        void print() {
            System.out.println(value);
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("Inner 对象被回收");
            super.finalize();
        }
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Outer 对象被回收");
        super.finalize();
    }
}
java 复制代码
public class Test {
    public static void main(String[] args) {
        Outer outer = new Outer();
        Outer.Inner inner = outer.new Inner();
        inner.print();

        System.out.println("----- outer 被设置为 null");

        outer = null;
        System.gc();
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("----- inner 被设置为 null");

        inner = null;
        System.gc();
        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码
# 输出结果

Outer
----- outer 被设置为 null
----- inner 被设置为 null
Inner 对象被回收
Outer 对象被回收
  1. 不合理的作用域:将局部变量提升为静态变量,意外延长对象生命周期

  2. 监听器或回调未注销:注册了监听器或回调,但是缺少移除方法

  3. ThreadLocal 使用不当:例如,线程池的线程复用时,ThreadLocal 未及时调用 remove 方法,导致数据残留

相关推荐
颜进强7 小时前
01 · NestJS 是什么:用途、解决什么问题、与热门框架对比
前端·后端·ai编程
isfox7 小时前
MapReduce Shuffle 深度解析:数据从 Map 到 Reduce 的完整旅程
后端
颜进强7 小时前
04 · NestJS 依赖注入:你在 `@Module` 写的 providers,和构造参数里那个类型,是怎么"对上"的?
前端·后端·ai编程
MayBaymax7 小时前
MongoDB 索引与事务
java·数据库·mongodb
学习中的码虫7 小时前
网络编程5
服务器·网络
vx-程序开发7 小时前
【计算机毕设】django校园跑腿服务系统83141
java·数据库·vue.js·spring boot·spring·elasticsearch·django
谁在黄金彼岸7 小时前
Ollama-使用速查
后端
ServBay7 小时前
Jev是什么?哑巴模型居然全网爆火
后端·aigc·ai编程
勇气要爆发8 小时前
006.注解
java·注解
烈风逍遥8 小时前
第六篇:RAG 知识库构建与检索全链路
前端·人工智能·后端