Java和Android开发中如何使用WeakReference?
我担任 Java 开发人员已有 2 年了。
但我从未在代码中编写过 WeakReference。如何使用 WeakReference 使我的应用程序更加高效,尤其是 Android 应用程序?
I have been a Java developer for 2 years.
But I have never written a WeakReference in my code. How to use WeakReference to make my application more efficient, especially the Android application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Android 中使用
WeakReference
与在普通的旧 Java 中使用弱引用没有任何不同。每当您需要对象的引用,但您不希望该引用保护该对象免受垃圾收集器的侵害时,您就应该考虑使用它。一个典型的例子是当内存使用率过高时您希望对其进行垃圾收集的缓存(通常使用
WeakHashMap
实现)。请务必查看
SoftReference
和PhantomReference
。编辑: Tom 对使用
WeakHashMap
实现缓存提出了一些担忧。这是一篇列出问题的文章: WeakHashMap 不是缓存!汤姆是对的,有投诉由于
WeakHashMap
缓存,Netbeans 性能较差。我仍然认为使用
WeakHashMap
实现缓存,然后将其与您自己使用SoftReference
实现的手动缓存进行比较,这将是一次很好的学习体验。在现实世界中,您可能不会使用这些解决方案中的任何一个,因为使用像 Apache JCS。Using a
WeakReference
in Android isn't any different than using one in plain old Java.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
).Be sure to check out
SoftReference
andPhantomReference
as well.EDIT: Tom has raised some concerns over implementing a cache with
WeakHashMap
. Here is an article laying out the problems: WeakHashMap is not a cache!Tom is right that there have been complaints about poor Netbeans performance due to
WeakHashMap
caching.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 withSoftReference
. 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.[EDIT2]我发现了
WeakReference
的另一个很好的例子。 脱离 UI 线程处理位图 页面中的 高效显示位图培训指南,展示了 AsyncTask 中WeakReference
的一种用法。它说,
快乐编码!
[编辑] 我从 facebook- 找到了一个非常好的
WeakReference
示例android-sdk。 ToolTipPopup 类什么都没有而是一个简单的小部件类,在锚视图上方显示工具提示。我截图了。该类非常简单(大约 200 行),值得一看。在该类中,WeakReference 类用于保存对锚视图的引用,这非常有意义,因为即使工具提示实例的生存时间比其锚视图长,它也可以使锚视图被垃圾回收。
快乐编码! :)
让我分享一个
WeakReference
类的工作示例。这是来自 Android 框架小部件的一个小代码片段,名为AutoCompleteTextView
。简而言之,
WeakReference
类是用来保存View
对象来防止本例中存在内存泄漏。我只需复制并粘贴 PopupDataSetObserver 类,它是 AutoCompleteTextView 的嵌套类。这真的很简单,注释很好地解释了课程。快乐编码! :)
并且
PopupDataSetObserver
用于设置适配器。最后一件事。我还想了解 Android 应用程序中
WeakReference
的工作示例,我可以在其官方示例应用程序中找到一些示例。但有些用法我实在是看不懂。例如,ThreadSample 和 DisplayingBitmaps 应用程序在其代码中使用WeakReference
,但在运行多次测试后,我发现 get () 方法永远不会返回null
,因为引用的视图对象在适配器中被回收,而不是被垃圾回收。[EDIT2] I found another good example of
WeakReference
. Processing Bitmaps Off the UI Thread page in Displaying Bitmaps Efficiently training guide, shows one usage ofWeakReference
in AsyncTask.It says,
Happy coding!
[EDIT] I found a really good example of
WeakReference
from facebook-android-sdk. ToolTipPopup class is nothing but a simple widget class that shows tooltip above anchor view. I captured a screenshot.The class is really simple(about 200 lines) and worthy to look at. In that class,
WeakReference
class is used to hold reference to anchor view, which makes perfect sense, because it makes possible for anchor view to be garbage collected even when a tooltip instance lives longer than its anchor view.Happy coding! :)
Let me share one working example of
WeakReference
class. It's a little code snippet from Android framework widget calledAutoCompleteTextView
.In short,
WeakReference
class is used to holdView
object to prevent memory leak in this example.I'll just copy-and-paste PopupDataSetObserver class, which is a nested class of
AutoCompleteTextView
. It's really simple and the comments explains the class well. Happy coding! :)And the
PopupDataSetObserver
is used in setting adapter.One last thing. I also wanted to know working example of
WeakReference
in Android application, and I could find some samples in its official sample applications. But I really couldn't understand some of them's usage. For example, ThreadSample and DisplayingBitmaps applications useWeakReference
in its code, but after running several tests, I found out that the get() method never returnsnull
, because referenced view object is recycled in adapters, rather then garbage collected.其他一些答案似乎不完整或太长。这是一个一般性的答案。
如何在 Java 和 Android 中使用 WeakReference
您可以执行以下步骤:
WeakReference
变量代码
MyClass< /code> 对
AnotherClass
有弱引用。AnotherClass
对MyClass
有很强的引用。注意
MyClass
是 A,AnotherClass
是 B。WeakReference
的替代方法是让另一个类实现接口。这是在监听器/观察者模式中完成的。实际示例
Some of the other answers seem incomplete or overly long. Here is a general answer.
How to use WeakReference in Java and Android
You can do the following steps:
WeakReference
variableCode
MyClass
has a weak reference toAnotherClass
.AnotherClass
has a strong reference toMyClass
.Notes
MyClass
was A andAnotherClass
was B.WeakReference
is to have another class implement an interface. This is done in the Listener/Observer Pattern.Practical example
“规范化”映射是指将相关对象的一个实例保留在内存中,而所有其他实例则通过指针或某种此类机制查找该特定实例。这就是弱引用可以发挥作用的地方。
简短的答案是,WeakReference 对象可用于创建指向系统中对象的指针,同时仍然允许这些对象在超出系统范围后被垃圾收集器回收。范围。例如,如果我有这样的代码:
我注册的任何对象都不会被 GC 回收,因为它的引用存储在
registeredObjects
集中。另一方面,如果我这样做:那么当 GC 想要回收 Set 中的对象时,它将能够这样做。
您可以使用此技术进行缓存、编目等。有关 GC 和缓存的更深入讨论的参考资料,请参阅下文。
参考:垃圾收集器和 WeakReference
A "canonicalized" mapping is where you keep one instance of the object in question in memory and all others look up that particular instance via pointers or somesuch mechanism. This is where weaks references can help.
The short answer is that WeakReference objects can be used to create pointers to objects in your system while still allowing those objects to be reclaimed by the garbage-collector once they pass out of scope. For example if I had code like this:
Any object I register will never be reclaimed by the GC because there is a reference to it stored in the set of
registeredObjects
. On the other hand if I do this:Then when the GC wants to reclaim the objects in the Set it will be able to do so.
You can use this technique for caching, cataloguing, etc. See below for references to much more in-depth discussions of GC and caching.
Ref: Garbage collector and WeakReference