`
leonzhx
  • 浏览: 771274 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论
阅读更多

1.  An obsolete reference is simply a reference that will never be dereferenced again.

 

2.  Memory leaks in garbage-collected languages (more properly known as unintentional object retentions) are insidious.

 

3.  If an object reference is unintentionally retained, not only is that object excluded from garbage collection, but so too are any objects referenced by that object, and so on.

 

4.  null out references once they become obsolete.

 

5.  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. This occurs naturally if you define each variable in the narrowest possible scope.

 

6.  Whenever a class manages its own memory (i.e. object array), the programmer should be alert for memory leaks. Another common source of memory leaks is caches.

 

7.  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; entries will be removed automatically after they become obsolete. Remember that WeakHashMap is useful only if the desired lifetime of cache entries is determined by external references to the key, not the value.

 

8.  Under these circumstances, the cache should occasionally be cleansed of entries that have fallen into disuse. This can be done by a background thread (perhaps a Timer or ScheduledThreadPoolExecutor) or as a side effect of adding new entries to the cache. The LinkedHashMap class facilitates the latter approach with its removeEldestEntry method.

 

9.  A third common source of memory leaks is listeners and other callbacks. If you implement an API where clients register callbacks but don’t deregister them explicitly, they will accumulate unless you take some action. The best 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.

 

10.  For more sophisticated caches, you may need to use java.lang.ref directly.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics