Are anonymous listeners incompatible with weak references?

放肆的年华 提交于 2019-12-03 05:08:30

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.

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.

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

Note: WeakHashMap i.a. uses weak references for its own subclass of Map.Entry. Which may at times be quite mind boggling.

If an object is only a key of a WeakHashMap, then it is eligible and likely to cleaned up on the next GC.

The whole idea of using a Weak referenced collection, is to implicitly remove listeners which are no longer referenced. (This avoid the potential for a memory leak) The problem is the listener can be removed prematurely and at a "random" point in time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!