如何避免回调中的内存泄漏? [英] How to avoid memory leaks in callback?

查看:740
本文介绍了如何避免回调中的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有效的Java说:


第三个内存泄漏的常见来源
是监听器和其他回调。如果
实现一个API,其中客户端
注册回调,但不是
明确注销它们,他们将
累积,除非你采取一些
操作。确保
回调是垃圾收集的最好方法
立即是只存储弱的
引用它们,例如,通过
存储它们作为键在
WeakHashMap。

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.

我是Java的初学者。可能有人教我如何创建弱引用回调,告诉我他们如何解决内存泄漏问题?感谢。

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.

推荐答案

阅读文章

关键是:


你可以将直接引用视为
强引用,不需要
编码以创建或访问
对象。剩余的三种类型的
引用是在
java.lang.ref包中找到的
引用类的子类。软引用
由SoftReference
类提供,弱引用由
WeakReference类提供,phantom
引用由PhantomReference引用。

You can think of direct references as strong references that require no extra coding to create or access the object. The remaining three types of references are subclasses of the Reference class found in the java.lang.ref package. Soft references are provided by the SoftReference class, weak references by the WeakReference class, and phantom references by PhantomReference.

软引用就像数据缓存。
当系统内存低时,垃圾
收集器可以随意释放一个
对象,该对象的唯一引用是软
引用。换句话说,如果
不是对一个对象的强引用,
那个对象是
release的候选对象。垃圾回收器是
需要在抛出
OutOfMemoryException之前释放任何软
引用。

Soft references act like a data cache. When system memory is low, the garbage collector can arbitrarily free an object whose only reference is a soft reference. In other words, if there are no strong references to an object, that object is a candidate for release. The garbage collector is required to release any soft references before throwing an OutOfMemoryException.

弱引用比软
引用弱。如果对
的唯一引用是弱引用,则
垃圾收集器可以随时回收对象使用的
内存。
不需要低
内存情况。通常,对象使用的内存
在垃圾收集器的
下一步中被回收。

Weak references are weaker than soft references. If the only references to an object are weak references, the garbage collector can reclaim the memory used by an object at any time. There is no requirement for a low memory situation. Typically, memory used by the object is reclaimed in the next pass of the garbage collector.

虚拟引用与清理
任务相关。他们提供一个通知
立即垃圾
收集器执行完成
进程和释放一个对象。考虑
它是一个在
对象内清除任务的方式。

Phantom references relate to cleanup tasks. They offer a notification immediately before the garbage collector performs the finalization process and frees an object. Consider it a way to do cleanup tasks within an object.

后面跟着WeakListModel列表将不会发布,以避免混乱此响应。

followed by the WeakListModel listing which I won't post to avoid cluttering this response.

这篇关于如何避免回调中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆