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

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

官方定义的引用类是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的删除无用值操作中会比较有效。软引用和弱引用之间的区别是于在决定将当前引用添加到引用队列并清除该引用的时间点不同。系统应该尽可能晚的来清除软引用和将其放入引用队列中,除非虚拟机内存严重不足。而对于虚引用,一旦被发现是虚引用,应该尽可能早的将其清除。

更多相关文章

  1. macos编译opencv+contrib+nonfree 4.2 for android
  2. 关于Android内存管理及性能优化的一些细节
  3. android ps 命令执行后各项值的含义
  4. 关于Unable to execute dex: Java heap space 解决办法
  5. android中的R中属性获取相关
  6. [android]动态查询手机内存
  7. java.lang.OutOfMemoryError: bitmap size exceeds VM budget
  8. Android(安卓)异步 RxAndroid框架官方例子
  9. Ubuntu下Chromium for Android(安卓)源码的编译

随机推荐

  1. android删除第三方jar的方法
  2. Android-->Android(安卓)原生支持圆角图
  3. View 的 android:visibility属性的讨论
  4. Eclipse+CDT+GDB调试Android(安卓)NDK程
  5. Android(安卓)如何将Canvas上绘制的内容
  6. 第二个Activity和Android(安卓)ListView
  7. android Notification (2)
  8. 2018-06-15 Android加载GIF图片的两种方
  9. Android传感器分析 seneor
  10. 【转】Android(安卓)Audio System