Pros and Cons of Listeners as WeakReferences

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

    This is not a complete answer, but the very strength you cite can also be its principal weakness. Consider what would happen if action listeners were implemented weakly:

    button.addActionListener(new ActionListener() {
        // blah
    });
    

    That action listener is going to get garbage collected at any moment! It's not uncommon that the only reference to an anonymous class is the event to which you are adding it.

提交回复
热议问题