常见的Java内存/引用泄漏模式? [英] Common Java memory/reference leak patterns?

查看:111
本文介绍了常见的Java内存/引用泄漏模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许最典型的例子是JDBC关闭错误,并且没有正确处理可能的异常。我很好奇看到你看过的其他例子 - 最好是与web应用程序有关。



那么,Java中是否存在任何常见的泄漏模式?

解决方案

根据我的经验,两个关键的有效泄漏模式是:随着时间的推移逐渐增长的静态和单身。这可能包括缓存,实施不当和使用的连接池,我们从启动以来见过的每个用户的字典等。

  • 将长寿命对象引用到目标是短暂的。在C#中,这可能发生在事件中,并且等效的观察者模式可能会在Java中产生相同的效果。基本上,如果你要求一个对象(观察者)观看另一个对象(源代码),那么你通常最终得到一个从源的观察者的引用。这可能最终成为唯一的实时参考,但它的寿命将与源一样长。

  • 如果您继续动态生成新代码,则会发生泄漏。我在这里摇摆不定,但我很确定我遇到了这样的问题。这可能部分是由于JRE bug已经被修复了 - 这种情况发生的时间太长了,因为我发现它确实存在。

  • 保持状态的单元测试可以持续比您可能会期望,因为JUnit将坚守测试用例实例。再次,我不记得细节,但有时候这样做值得在拆解时使用明确的变量归零,因为它看起来不合时宜。 b
    $ b

    我不能说我经常发现内存泄漏是Java(或.NET)中的问题。


    Maybe the most typical example is the JDBC closing done wrong way and not handling the possible exceptions correctly. I am very curious to see other examples you have seen - preferably web application related.

    So, are there any common leak patterns in Java?

    解决方案

    The two key "effective leak" patterns in my experience are:

    • Statics and singletons which gradually grow over time. This could include caches, poorly implemented and used connection pools, dictionaries of "every user we've seen since startup" etc
    • References from long-lived objects to objects which were intended to be short-lived. In C# this can happen with events, and the equivalent observer pattern could give the same sort of effect in Java. Basically if you ask one object (the observer) to watch another (the source) then you usually end up with a reference from the source to the observer. That can end up being the only "live" reference, but it'll live as long as the source.
    • Permgen leaks if you keep generating new code dynamically. I'm on rockier ground here, but I'm pretty sure I've run into problems this way. It's possible this was partly due to JRE bugs which have since been fixed - it's been too long since it happened for me to remember for sure.
    • Unit tests which hold onto state can last longer than you might expect because JUnit will hold onto the testcase instances. Again I can't remember the details, but sometimes this makes it worth having explicit "variable nulling" in the teardown, anachronistic as that looks.

    I can't say that I've regularly found memory leaks to be a problem in Java (or .NET) though.

    这篇关于常见的Java内存/引用泄漏模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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