笔记
whenever a class manages its own memory, the programmer should be alert for memory leaks.
手动内存管理都有内存泄露的危险。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实现缓存。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.
内存泄露很难搞。尤其是java程序员,没有经历过c/c++开发的历练,这方面能力更为欠缺。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的自动垃圾收集,解决的是手工释放对象的问题,这只是导致内存泄露的一部分原因。一定要格外注意对象的引用。对于长久运行的程序部分,要注意管理其中的对象生命周期,用不到的对象就要去掉引用,让jvm回收掉它。
- 缓存,容器还有回调等场景要注意内存泄露问题。