如何在 Java 中创建内存泄漏? [英] How can I create a memory leak in Java?

查看:24
本文介绍了如何在 Java 中创建内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚接受了一次采访,要求我使用 Java 创建内存泄漏.

I just had an interview where I was asked to create a memory leak with Java.

不用说,我什至不知道如何开始创建一个,我觉得很愚蠢.

Needless to say, I felt pretty dumb having no clue on how to even start creating one.

一个例子是什么?

推荐答案

持有对象引用的静态字段 [尤其是 final 字段]

class MemorableClass {
    static final ArrayList list = new ArrayList(100);
}

调用 String.intern() 在一个长字符串上

String str = readString(); // read lengthy string any source db,textbox/jsp etc..
// This will place the string in memory pool from which you can't remove
str.intern();

(未封闭的)开放流(文件、网络等)

try {
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    ...
    ...
} catch (Exception e) {
    e.printStacktrace();
}

未关闭的连接

try {
    Connection conn = ConnectionFactory.getConnection();
    ...
    ...
} catch (Exception e) {
    e.printStacktrace();
}

JVM 垃圾收集器无法访问的区域,例如通过本机方法分配的内存.

Areas that are unreachable from JVM's garbage collector, such as memory allocated through native methods.

在 Web 应用程序中,一些对象存储在应用程序范围内,直到应用程序被明确停止或删除.

In web applications, some objects are stored in application scope until the application is explicitly stopped or removed.

getServletContext().setAttribute("SOME_MAP", map);

不正确或不适当的 JVM 选项,例如 IBM JDK 上的 noclassgc 选项可防止未使用的类垃圾收集

Incorrect or inappropriate JVM options, such as the noclassgc option on IBM JDK that prevents unused class garbage collection

参见 IBM JDK 设置.

这篇关于如何在 Java 中创建内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆