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 方法,导致数据残留

相关推荐
HackTwoHub1 分钟前
等级保护现场测评系统重磅更新,支持 AI 接入,可录入全品类资产清单,自动化巡检核查,批量导出测评归档文件
运维·人工智能·安全·web安全·网络安全·自动化·系统安全
buhuizhiyuci5 分钟前
【算法篇】位运算 —— 基础篇
java·数据库·算法
川石课堂软件测试8 分钟前
安全测试|服务器安全加固方法
服务器·功能测试·测试工具·jmeter·mysql·web安全·单元测试
卷无止境16 分钟前
Python itertools 盘点真正用得上的20个常用方法
后端
2401_8582861122 分钟前
OS79.【Linux】POSIX信号量
linux·运维·服务器
laboratory agent开发25 分钟前
企业AI Agent落地前,先回答四个工程问题
java·前端·人工智能
微三云 - 廖会灵 (私域系统开发)26 分钟前
电商系统国际化架构设计:多语言、多币种、多时区、多税制的全链路实现
java·前端·数据库
XS03010626 分钟前
Spring AI 第二课-流式输出 & 运行时动态参数配置
java·人工智能·spring
公众号:fuwuqiBMC28 分钟前
(转自“服务器BMC”)服务器BMC功能——DDR故障预测
运维·服务器·人工智能
孬甭_29 分钟前
C++ string类
开发语言·c++