java - 如何避免回调中的内存泄漏?

标签 java memory-management callback weak-references

Effective Java 说:

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 初学者。有人可以教我如何在回调中创建弱引用并告诉我他们如何解决内存泄漏问题吗?谢谢。

最佳答案

阅读 this文章

关键要点是:

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.

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 列表,我不会发布该列表以避免困惑此响应。

关于java - 如何避免回调中的内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2859464/

相关文章:

java - 异步任务无法更新 GUI

java - @Option(longName = "fileName") 在Java中是什么意思?

java - 使用 JApplet 创建动画

c++ - 在这种情况下如何有效地使用 intrusive_ptr?

linux - 内存在 32 位系统中未使用?

c - C编程内存复制和删除失败

javascript - 将正确的 "this"上下文传递给 setTimeout 回调?

c++ - 将私有(private)方法类成员作为指向函数的指针传递

java - mac 上的进程外视频播放器 (vlcj)

python - 如何制作一个用CFFI包裹的C-DLL来回调python