自由飛翔

          我在仰望,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 閱讀(358) 評論(0)  編輯  收藏 所屬分類: corejava

          主站蜘蛛池模板: 郁南县| 云阳县| 电白县| 托克托县| 九龙坡区| 阿拉善右旗| 铁岭市| 棋牌| 安化县| 平阳县| 湄潭县| 正阳县| 时尚| 南丰县| 汕头市| 岑巩县| 临夏县| 赞皇县| 太保市| 台东市| 武清区| 汪清县| 无极县| 错那县| 伊宁市| 武山县| 留坝县| 泸州市| 洪江市| 始兴县| 密云县| 重庆市| 盘锦市| 左权县| 呈贡县| 自治县| 松潘县| 玉田县| 连南| 宁陵县| 华坪县|