匿名侦听器与弱引用是否不兼容?

编程入门 行业动态 更新时间:2024-10-27 03:39:25
本文介绍了匿名侦听器与弱引用是否不兼容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在阅读这个问题:避免回拨时出现内存泄漏?

我很困惑,直到有人回答了以下问题:

And I was quite confused, until someone answered the following:

这个方法的问题是你不能有一个监听器只在集合中引用,因为它会随机消失(在下一个GC上)

我通常会传递如下的侦听器:

I typically pass listeners like this:

public static void main(String[] args) { final Observable obs = new SomeObservable(); obs.addObserver(new Observer() { public void update(final Observable o, final Object arg) { System.out.println("Notified"); } }); obs.notifyObservers(); ... // program continues its life here } private static final class SomeObservable extends Observable { @Override public void addObserver(final Observer o) { super.addObserver(o); setChanged(); // shouldn't be done from here (unrelated to the question) } }

我使用一个 CopyOnWriteArrayList 来跟踪监听器(上面的默认 Observable 显然使用了一个旧的向量它只是一个例子,显示我通常创建一个匿名类用作监听器)。

And I keep track of the listeners using a CopyOnWriteArrayList (the default Observable above apparently uses an old Vector but its just an example to show how I typically create an anonymous class to use as a listener).

作为一个红利的问题:什么时候对匿名监听器的引用对于GC,可观察的主体使用WeakHashMap?当 main 方法退出时?一旦 obs.addObserver 调用结束了?

As a bonus question: when would the reference to the anonymous listener be eligible for GC should the observable subject use a WeakHashMap? When the main method exits? As soon as the obs.addObserver call is over?

我有点困惑的地方/如何/当引用匿名类实例

I'm a bit confused about where/how/when references to anonymous class instances are kept/stored/elligible for GC.

显然,如果我保持正常引用,它不适用于GC,但是当它在WeakHashMap中时,

Obviously if I'm keeping a normal reference it's not eligible for GC, but what when it's in a WeakHashMap, when does precisely the listener become elligible for GC?

推荐答案

是的,你是对的,一个可监听的类保持具有弱引用的侦听器(如WeakHashMap)需要它们的独立持久性。

Yes, you are right, a listenable class maintaining the listeners with weak references (as does WeakHashMap) requires their independent persistence. Could be used for listener hierarchies where a listener has children and a parent.

对于非WeakReference用法,必须调用一个显式的removeListener。除非监听器对象可以和可监听对象一样长。

For non-WeakReference usages an explicit removeListener must be called. Unless the listener object may live as long as the listenable object. In most use cases that is fine, and an anonymous class will do.

对于匿名类实例, leak (GC预防)只能发生当访问类身体之外的最终对象时。

With anonymous class instances a leak (GC prevention) may only happen when accessing a final object outside the class body.

注意:WeakHashMap ia对其自己的Map.Entry子类使用弱引用。这有时可能会令人难以置信。

更多推荐

匿名侦听器与弱引用是否不兼容?

本文发布于:2023-11-09 23:14:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573704.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:侦听器   不兼容

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!