自由飞翔

我在仰望,java之上

统计

留言簿(2)

我关注的blog

阅读排行榜

评论排行榜

谈谈memory leak

参考文章:

malloc/free和new/delete必须成对出现,以防止内存泄露

一、什么时候垃圾回收:
简单说:
当一块内存被jvm通过它自己的认证机制认为不再被调用的时候才会在
它认为合适的时机进行回收;
具体说:

The job of the garbage collector is to find objects that are no longer needed by an application and to remove them when they can no longer be accessed or referenced. The garbage collector starts at the root nodes, classes that persist throughout the life of a Java application, and sweeps through all of the nodes that are referenced. As it traverses the nodes, it keeps track of which objects are actively being referenced. Any classes that are no longer being referenced are then eligible to be garbage collected. The memory resources used by these objects can be returned to the Java virtual machine (JVM) when the objects are deleted.

So it is true that Java code does not require the programmer to be responsible for memory management cleanup, and that it automatically garbage collects unused objects. However, the key point to remember is that an object is only counted as being unused when it is no longer referenced.

垃圾收集器的工作是找到由一个应用程序不再需要的对象,在他们不再被访问或引用将其删除。垃圾收集器从根节点、在整个Java应用的生命中存在的类
开始,并通过扫描所有被引用的节点。由于它遍历的节点,它跟踪哪些对象正在积极引用。任何不再被引用的的类,然后才有资格被垃圾收集。
当对象被删除时,他们所占用的内存资源,才被Java虚拟机(JVM)回收。
二、什么样的java代码容易memory leak?
1.
首先一种情况是collection或者是map一直被put数据,没有机会remove,导致OutOfMemoryError。尤其是当collection或者是map被设计成static变量的时候,它就是个global性质的变量,很可能永远不会被赋为null。这也是不建议使用static变量的一个原因。
2.
在listener的模式下,如果listener一直在注册register而没有机会remove也会导致OutOfMemoryError。其实listener也是一个list的结构,本质上是一样的。很多listener是以匿名类被构造和注册到被监听类上面去的, 而被监听类如果也没有正确remove注册的listener的话也会导致OutOfMemoryError。


待续...........


Gavin

posted on 2011-09-07 14:04 GavinMiao 阅读(346) 评论(0)  编辑  收藏 所属分类: corejava


只有注册用户登录后才能发表评论。


网站导航: