如何在Java和Android开发使用的WeakReference? [英] How to use WeakReference in Java and Android development?
问题描述
我一直是Java开发人员2年。
I have been a java developer for 2 years.
不过,我从来没有在我的code写一个WeakReference的。如何使用WeakReference的,使我的应用程序更有效率尤其是Android应用?
But I have never wrote a WeakReference in my code. How to use WeakReference to make my application more efficient especially the Android application?
推荐答案
使用的WeakReference
在Android中并不比普通的Java使用一个有什么不同。这是一个伟大的指南,给出了详细的解释:理解弱引用
Using a WeakReference
in Android isn't any different than using one in plain old Java. Here is a great guide which gives a detailed explanation: Understanding Weak References.
您应该考虑使用一个,只要你需要引用一个对象,但你不希望出现这种情况的参考,以保护对象从垃圾收集器。一个典型的例子是,你要被垃圾回收时,内存占用过高的高速缓存(通常与实施的WeakHashMap
)。
You should think about using one whenever you need a reference to an object, but you don't want that reference to protect the object from the garbage collector. A classic example is a cache that you want to be garbage collected when memory usage gets too high (often implemented with WeakHashMap
).
一定要看看 SoftReference
和的PhantomReference
和
编辑:汤姆提出了一些担忧与实施的WeakHashMap
缓存。这是一篇文章奠定了存在的问题:<一href="http://www.$c$cinstructions.com/2008/09/weakhashmap-is-not-cache-understanding.html">WeakHashMap是不是缓存!
Tom has raised some concerns over implementing a cache with WeakHashMap
. Here is an article laying out the problems: WeakHashMap is not a cache!
汤姆是正确的,有过投诉有关不佳Netbeans的性能,因为 WeakHashMap中
缓存。
Tom is right that there have been complaints about poor Netbeans performance due to WeakHashMap
caching.
我仍然认为这将是一个很好的学习经验,以实现与高速缓存的WeakHashMap
,然后针对与 SoftReference
。在现实世界中,你可能不会使用其中的解决方案,因为它使更多的意义,使用如的Apache JCS第三方库。
I still think it would be a good learning experience to implement a cache with WeakHashMap
and then compare it against your own hand-rolled cache implemented with SoftReference
. In the real world, you probably wouldn't use either of these solutions, since it makes more sense to use a 3rd party library like Apache JCS.
这篇关于如何在Java和Android开发使用的WeakReference?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!