Android Reference官方描述

本篇文章翻译自官方API部分内容:
https://developer.android.com/reference/java/lang/ref/Reference.html
https://developer.android.com/reference/java/lang/ref/WeakReference.html

一 官方对三种引用方式的简单描述:

Android Reference官方描述_第1张图片

官方定义的引用类是Reference,其下有三个子类,分别对应三种引用方式,分别是虚引用、软引用、弱引用。其中软引用是当内存不足需要清除的一种非强引用,虚引用的生命周期三者中是最短的,随时都会被回收。

二 官方对软引用的使用建议:

原文:Avoid Soft References for Caching In practice, soft references are inefficient for caching. The runtime doesn’t have enough information on which references to clear and which to keep. Most fatally, it doesn’t know what to do when given the choice between clearing a soft reference and growing the heap. The lack of information on the value to your application of each reference limits the usefulness of soft references. References that are cleared too early cause unnecessary work; those that are cleared too late waste memory. Most applications should use an android.util.LruCache instead of soft references. LruCache has an effective eviction policy and lets the user tune how much memory is allotted.

官方建议在实际缓存应用中,要避免使用软引用,一方面是因为软引用在缓存中并不高效,另一方面,运行时并没有充分的信息来判断哪些软引用需要清除,哪些需要保留。更致命的是,安卓系统在内存不足时并不能立即清除一个软引用,同时安卓系统内部缺乏一个限制无用的软引用的这样的机制。这些引用如果太早清除会造成不必要的开销,太晚清除会造成内存的浪费。因此,建议使用LruCache 代替soft references.,LruCache 有一个高效的内存回收机制,同时也能够让使用者按照具体需要的内存进行调整。

三 官方对软引用和弱引用的区别描述:

原文:Weak references are useful for mappings that should have their entries removed automatically once they are not referenced any more (from outside). The difference between a SoftReference and a WeakReference is the point of time at which the decision is made to clear and enqueue the reference: A SoftReference should be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory. A WeakReference may be cleared and enqueued as soon as is known to be weakly-referenced.

弱引用的自动清除机制(atomically cleared),使得弱引用在Map的删除无用值操作中会比较有效。软引用和弱引用之间的区别是于在决定将当前引用添加到引用队列并清除该引用的时间点不同。系统应该尽可能晚的来清除软引用和将其放入引用队列中,除非虚拟机内存严重不足。而对于虚引用,一旦被发现是虚引用,应该尽可能早的将其清除。

你可能感兴趣的:(android,弱引用,软引用)