导致Java中内存泄漏的最简单方法

问题描述:

可能重复:
使用Java创建内存泄漏

导致Java内存泄漏的最简单方法是什么?

What's the easiest way to cause a Java memory leak?

除非您执行以下操作,否则您无法在Java中真正泄漏内存":

You cannot really "leak memory" in Java unless you:

  • 实习生字符串
  • 生成类
  • jli调用的本机代码中的
  • 泄漏内存
  • 在一些被遗忘或晦涩的地方保留对您不想要的东西的引用.
  • 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:

  • 监听器,尤其是内部类
  • 缓存.

一个很好的例子是:

  • 构建一个Swing gui,它会启动可能无限数量的模态窗口;
  • 让模态窗口在初始化期间执行以下操作:
  • 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.

这就是为什么诸如EventBus之类的库默认使用弱引用的原因.

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.