如何避免回调中的内存泄漏?
有效的Java 说:
内存泄漏的第三个常见来源 是监听器和其他回调。如果 你实现了一个 API,其中客户端 注册回调但不注册 明确取消注册它们,他们会 积累,除非你采取一些 行动。确保的最好方法是 回调被垃圾收集 即刻是只存储弱 对它们的引用,例如 仅将它们作为键存储在 WeakHashMap。
我是 Java 初学者。有人可以教我如何在回调中创建弱引用并告诉我他们如何解决内存泄漏问题吗?谢谢。
Effective Java says:
A third common source of memory leaks
is listeners and other callbacks. If
you implement an API where clients
register callbacks but don’t
deregister them explicitly, they will
accumulate unless you take some
action. The best way to ensure that
callbacks are garbage collected
promptly is to store only weak
references to them, for instance, by
storing them only as keys in a
WeakHashMap.
I am a beginner in Java. Could somebody teach me how to create weak references in callbacks and tell me how they solve the memory leak problems? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
阅读 这篇文章的
要点是:
接下来是 WeakListModel 列表,我不会发布该列表以避免使此响应混乱。
Read this article
The key take aways are :
followed by the WeakListModel listing which I won't post to avoid cluttering this response.
为了用一个快速(粗略)示例来说明这个概念,请考虑以下情况:
如果客户端类随后使用此
FileMonitor
API,他们可能会这样做:如果
MyClass
的作者> 然后在处理程序完成后忘记调用unregisterChangeHandler()
,FileMonitor
的HashSet
将永远引用已注册的实例,使其保留在内存中,直到 FileMonitor 被销毁或应用程序退出。为了防止这种情况,Bloch 建议使用弱引用集合而不是
HashSet
,这样,如果您的MyClass
实例被销毁,该引用将从监视器的收藏。您可以将
FileMonitor
中的HashSet
替换为WeakHashMap
并使用处理程序作为键,因为当对该对象的所有其他引用都消失时,后者会自动从集合中删除处理程序。To illustrate the concept with a quick (crude) example, consider the following:
If a client class then uses this
FileMonitor
API, they might do this:If the author of the
MyClass
then forgets to callunregisterChangeHandler()
when it's done with the handler, theFileMonitor
'sHashSet
will forever reference the instance that was registered, causing it to remain in memory until theFileMonitor
is destroyed or the application quits.To prevent this, Bloch is suggesting using a weak-referencing collection instead of the
HashSet
, so that if your instance ofMyClass
is destroyed, the reference will be removed from the monitor's collection.You might replace the
HashSet
inFileMonitor
with aWeakHashMap
and use the handlers as the keys, since the latter will automatically remove the handler from the collection when all other references to the object are gone.在这里您还可以找到清晰且实用解释:
Android 中的内存泄漏 — 识别、治疗和避免
Here you may find a clear and practical explanation as well:
Memory leaks in Android — identify, treat and avoid