如何在 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 设置.