您现在的位置是:首页 > 文章详情

为什么Android官方废弃SoftRefrerence软引用和WeakReference弱引用,而拥抱LruCache?

日期:2018-06-08点击:422

为什么Android官方废弃SoftRefrerence软引用和WeakReference弱引用,而拥抱LruCache?


一些具有Java背景的研发者喜欢使用软引用(SoftRefrerence)和弱引用(WeakReference)来缓存Java对象和数据,但是如果在Android中仍然使用软引用(SoftRefrerence)和弱引用(WeakReference),会极易导致Android程序闪退崩溃,谷歌Android官方从Android 3.0以后,强烈建议开发者不要在Android中使用软引用(SoftRefrerence)和弱引用(WeakReference),Android的谷歌官方解释(原文):
Note: In the past, a popular memory cache implementation was a SoftReference or WeakReference bitmap cache, however this is not recommended. Starting from Android 2.3 (API Level 9) the garbage collector is more aggressive with collecting soft/weak references which makes them fairly ineffective. In addition, prior to Android 3.0 (API Level 11), the backing data of a bitmap was stored in native memory which is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.
官方文档链接见附录3。
这段内容大致翻译出来是这样的(英文对照翻译):
Note: In the past, a popular memory cache implementation was a SoftReference or WeakReference bitmap cache, however this is not recommended. Starting from Android 2.3 (API Level 9) the garbage collector is more aggressive with collecting soft/weak references which makes them fairly ineffective. In addition, prior to Android 3.0 (API Level 11), the backing data of a bitmap was stored in native memory which is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. 注意!在过去,一个非常流行的内存缓存实现是通过SoftReference或WeakReference对bitmap进行缓存,然而现在不推荐使用这种方案实施内存缓存了。从Android系统版本2.3 ( API Level 9 )以后,garbage collector(译者注:Java垃圾回收器)会更加积极的回收持有软/弱引用对象,这导致软引用和弱引用变的相当无能为力。除此之外,在Android系统版本3.0 ( API Level 11 )之前,在本地内存中缓存一个bitmap数据并不会以预期的方式释放,这可能导致一个应用在很短期间就超越它的内存上限(译者注:进而会引发OOM,Out Of Memory)而导致应用崩溃。
同样在官方文档链接下面,谷歌Android官方给出了在Android中处理缓存应该使用什么样的缓存策略:采用LruCache。关于LruCache,请看我过去写的附录文章1和2。
时至今日,网上搜一搜Android缓存技术,有感于当下竟然还有一些文章在给开发者推荐使用SoftRefrerence软引用和WeakReference弱引用缓存数据,不禁令人唏嘘。


附录:
1,《使用Android新式LruCache缓存图片,基于线程池异步加载图片》链接:https://blog.csdn.net/zhangphil/article/details/44082287 
2,《使用新式LruCache取代SoftReference缓存图片,Android异步加载图片》链接:https://blog.csdn.net/zhangphil/article/details/43667415 
3,Android谷歌官方解释为何要极力避免在Android程序中使用WeakReference弱引用与SoftReference软引用?谷歌官方英文文档链接地址:http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
原文链接:https://yq.aliyun.com/articles/615648
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章