在 Java 中导致内存泄漏的最简单方法 [英] Easiest way to cause a memory leak in Java
问题描述
可能的重复:
使用 Java 造成内存泄漏
导致 Java 内存泄漏的最简单方法是什么?
你不能真正泄漏内存"在 Java 中,除非您:
- 实习生字符串
- 生成类
- 由 JNI 调用的本机代码中的内存泄漏
- 将您不想要的东西放在被遗忘或晦涩的地方.
我认为您对最后一个案例感兴趣.常见的场景有:
- 监听器,尤其是内部类
- 缓存.
一个很好的例子是:
- 构建一个可以启动无限数量的模态窗口的 Swing GUI;
- 让模态窗口在初始化期间做这样的事情:<代码><预>StaticGuiHelper.getMainApplicationFrame().getOneOfTheButtons().addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){//没做什么...}})
注册的动作什么都不做,但它会导致模态窗口永远留在内存中,即使在关闭之后,导致泄漏——因为监听器永远不会被取消注册,并且每个匿名内部类对象都持有一个引用(不可见)到它的外部对象.更重要的是 - 从模态窗口引用的任何对象也有可能泄漏.
这就是 EventBus 等库默认使用弱引用的原因.
除了监听器,其他典型的例子是缓存,但我想不出一个很好的例子.
Possible Duplicate:
Creating a memory leak with Java
What's the easiest way to cause a Java memory leak?
You cannot really "leak memory" in Java unless you:
- intern strings
- generate classes
- leak memory in the native code called by JNI
- keep references to things that you do not want in some forgotten or obscure place.
I take it that you are interested in the last case. The common scenarios are:
- listeners, especially done with inner classes
- caches.
A nice example would be to:
- build a Swing GUI that launches a potentially unlimited number of modal windows;
- have the modal window do something like this during its initialization:
StaticGuiHelper.getMainApplicationFrame().getOneOfTheButtons().addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ // do nothing... } })
The registered action does nothing, but it will cause the modal window to linger in memory forever, even after closing, causing a leak - since the listeners are never unregistered, and each anonymous inner class object holds a reference (invisible) to its outer object. What's more - any object referenced from the modal windows have a chance of leaking too.
This is why libraries such as EventBus use weak references by default.
Apart from listeners, other typical examples are caches, but I cannot think of a nice example.
这篇关于在 Java 中导致内存泄漏的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!