筆記
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)存泄露問題。