本文介绍了常见的Java内存/引用泄漏模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
也许最典型的例子是JDBC关闭错误,并且没有正确处理可能的异常。我很好奇看到你看过的其他例子 - 最好是与web应用程序有关。
那么,Java中是否存在任何常见的泄漏模式?
解决方案
根据我的经验,两个关键的有效泄漏模式是:随着时间的推移逐渐增长的静态和单身。这可能包括缓存,实施不当和使用的连接池,我们从启动以来见过的每个用户的字典等。
$ 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内存/引用泄漏模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!