Item 7: Eliminate obsolete object references

筆記

  • whenever a class manages its own memory, the programmer should be alert for memory leaks.
    手動內(nèi)存管理都有內(nèi)存泄露的危險。

  • Another common source of memory leaks is caches. Once you put an object reference into a cache, it’s easy to forget that it’s there and leave it in the cache long after it becomes irrelevant.
    緩存也一樣。

  • If you’re lucky enough to implement a cache for which an entry is relevant exactly so long as there are references to its key outside of the cache, represent the cache as a WeakHashMap。
    用 WeakHashMap實(shí)現(xiàn)緩存。

  • A third common source of memory leaks is listeners and other callbacks. One way to ensure that callbacks are garbage collected promptly is to store only weak references to them, for instance, by storing them only as keys in a WeakHashMap。
    不是很理解這種場景。

  • memory leaks typically do not manifest themselves as obvious failures, they may remain present in a system for years. They are typically discovered only as a result of careful code inspection or with the aid of a debugging tool known as a heap profiler.
    內(nèi)存泄露很難搞。尤其是java程序員,沒有經(jīng)歷過c/c++開發(fā)的歷練,這方面能力更為欠缺。

  • Nulling out object references should be the exception rather than the norm. The best way to eliminate an obsolete reference is to let the variable that contained the reference fall out of scope.
    這句話很有道理:最好的辦法是讓變量超出作用域。

理解與思考

  • java的自動垃圾收集,解決的是手工釋放對象的問題,這只是導(dǎo)致內(nèi)存泄露的一部分原因。一定要格外注意對象的引用。對于長久運(yùn)行的程序部分,要注意管理其中的對象生命周期,用不到的對象就要去掉引用,讓jvm回收掉它。
  • 緩存,容器還有回調(diào)等場景要注意內(nèi)存泄露問題。

實(shí)踐

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容