Pros and Cons of Listeners as WeakReferences

前端 未结 12 1014
天命终不由人
天命终不由人 2020-12-04 12:18

What are the pros and cons of keeping listeners as WeakReferences.

The big \'Pro\' of course is that:

Adding a listener as a WeakReference means the listener

12条回答
  •  情歌与酒
    2020-12-04 12:29

    I have 3 suggestions for the original poster. Sorry for resurrecting an old thread but I think my solutions were not previously discussed in this thread.

    First, Consider following the example of javafx.beans.values.WeakChangeListener in the JavaFX libraries.

    Second, I one upped the JavaFX pattern by modifying the addListener methods of my Observable. The new addListener() method now creates instances of the corresponding WeakXxxListener classes for me.

    The "fire event" method was easily modified to dereference the XxxWeakListeners and to remove them when the WeakReference.get() returned null.

    The remove method was now a bit nastier since I need to iterate the entire list, and that means I need to do synchronization.

    Third, Prior to implementing this strategy I employed a different method which you may find useful. The (hard reference) listeners got a new event they did a reality check of whether or not they were still being used. If not, then they unsubscribed from the observer which allowed them to be GCed. For short lived Listeners subscribed to long lived Observables, detecting obsolescence was fairly easy.

    In deference to the folks who stipulated that it was "good programming practice to always unsubscribe your listeners, whenever a Listener resorted to unsubscribing itself, I made sure to create a log entry and corrected the problem in my code later.

提交回复
热议问题