自由飛翔

          我在仰望,java之上

          統(tǒng)計

          留言簿(2)

          我關(guān)注的blog

          閱讀排行榜

          評論排行榜

          談?wù)刴emory leak

          參考文章:

          malloc/free和new/delete必須成對出現(xiàn),以防止內(nèi)存泄露

          一、什么時候垃圾回收:
          簡單說:
          當一塊內(nèi)存被jvm通過它自己的認證機制認為不再被調(diào)用的時候才會在
          它認為合適的時機進行回收;
          具體說:

          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.

          垃圾收集器的工作是找到由一個應(yīng)用程序不再需要的對象,在他們不再被訪問或引用將其刪除。垃圾收集器從根節(jié)點、在整個Java應(yīng)用的生命中存在的類
          開始,并通過掃描所有被引用的節(jié)點。由于它遍歷的節(jié)點,它跟蹤哪些對象正在積極引用。任何不再被引用的的類,然后才有資格被垃圾收集。
          當對象被刪除時,他們所占用的內(nèi)存資源,才被Java虛擬機(JVM)回收。
          二、什么樣的java代碼容易memory leak?
          1.
          首先一種情況是collection或者是map一直被put數(shù)據(jù),沒有機會remove,導(dǎo)致OutOfMemoryError。尤其是當collection或者是map被設(shè)計成static變量的時候,它就是個global性質(zhì)的變量,很可能永遠不會被賦為null。這也是不建議使用static變量的一個原因。
          2.
          在listener的模式下,如果listener一直在注冊register而沒有機會remove也會導(dǎo)致OutOfMemoryError。其實listener也是一個list的結(jié)構(gòu),本質(zhì)上是一樣的。很多l(xiāng)istener是以匿名類被構(gòu)造和注冊到被監(jiān)聽類上面去的, 而被監(jiān)聽類如果也沒有正確remove注冊的listener的話也會導(dǎo)致OutOfMemoryError。


          待續(xù)...........


          Gavin

          posted on 2011-09-07 14:04 GavinMiao 閱讀(359) 評論(0)  編輯  收藏 所屬分類: corejava

          主站蜘蛛池模板: 沧州市| 都匀市| 祁门县| 北川| 香格里拉县| 上林县| 河曲县| 赤水市| 内丘县| 布拖县| 宜昌市| 民丰县| 武平县| 广饶县| 紫阳县| 介休市| 浑源县| 都昌县| 锡林郭勒盟| 方城县| 闽侯县| 和龙市| 分宜县| 尚志市| 平利县| 阳东县| 广昌县| 福海县| 正安县| 阿拉善左旗| 通榆县| 揭阳市| 海兴县| 九寨沟县| 庐江县| 永登县| 涞源县| 盘锦市| 盐亭县| 石屏县| 若羌县|