Pros and Cons of Listeners as WeakReferences

前端 未结 12 1010
天命终不由人
天命终不由人 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

    In my opinion it's a good idea in most cases. The code that is responsible for releasing the listener is at the same place where it gets registered.

    In practice i see a lot of software which is keeping listeners forever. Often programmers are not even aware that they should unregister them.

    It usually is possible to return a custom object with a reference to the listener that allows manipulation of when to unregister. For example:

    listeners.on("change", new Runnable() {
      public void run() {
        System.out.println("hello!");
      }
    }).keepFor(someInstance).keepFor(otherInstance);
    

    this code would register the listener, return an object that encapsulates the listener and has a method, keepFor that adds the listener to a static weakHashMap with the instance parameter as the key. That would guarantee that the listener is registered at least as long as someInstance and otherInstance are not garbage collected.

    There can be other methods like keepForever() or keepUntilCalled(5) or keepUntil(DateTime.now().plusSeconds(5)) or unregisterNow().

    Default can be keep forever (until unregistered).

    This could also be implemented without weak references but phantom references that trigger the removal of the listener.

    edit: created a small lib which implements a basic version of this aproach https://github.com/creichlin/struwwel

提交回复
热议问题