在Java中导致内存泄漏的最简单方法? [英] Easiest way to cause memory leak in Java?

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

问题描述


可能重复:

使用Java创建内存泄漏

什么是造成java内存泄漏的最简单方法是什么?

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

推荐答案

除非你:


  • 实习生字符串

  • 生成课程

  • 本机代码中的内存泄漏由jni调用

  • 在某些被遗忘或模糊的地方保留对你不想要的东西的引用。

  • 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:


  • 听众,尤其是内部类

  • 缓存。

一个很好的例子是:


  • build启动可能无限数量的模态窗口的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.

这篇关于在Java中导致内存泄漏的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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