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

相关推荐
leo825...7 小时前
Claude Code Skills 清单(本地)
java·python·ai编程
csbysj20207 小时前
SQL NULL 函数详解
开发语言
其实防守也摸鱼7 小时前
CTF密码学综合教学指南--第三章
开发语言·网络·python·安全·网络安全·密码学
NGSI vimp7 小时前
Java进阶——如何查看Java字节码
java·开发语言
一起学开源8 小时前
企业级AI应用开发底座应该怎么设计?
人工智能·系统架构·智能体
草履虫君8 小时前
VMware 虚拟机网络性能优化指南:从 11 秒到 4 秒的完整调优实践
服务器·网络·经验分享·性能优化
We་ct8 小时前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
日取其半万世不竭8 小时前
LVM 逻辑卷管理:不停机扩容磁盘的正确方式
运维·服务器
身如柳絮随风扬9 小时前
多数据源切换实战:从业务场景到3种实现方案全解析
java·分布式·微服务
skywalk81639 小时前
在考虑双轨制,即在中文语法的基础上,加上数学公式的支持,这样像很多计算将更加简单方便,就像现在的小学数学课本里面一样,比如:定x=2*x + 1
开发语言