Pros and Cons of Listeners as WeakReferences

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

    It appears from a test program that anonymous ActionListeners will not prevent an object from being garbage collected:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    
    public class ListenerGC {
    
    private static ActionListener al = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.err.println("blah blah");
            }
        };
    public static void main(String[] args) throws InterruptedException {
    
        {
            NoisyButton sec = new NoisyButton("second");
            sec.addActionListener(al);
            new NoisyButton("first");
            //sec.removeActionListener(al);
            sec = null;
        }
        System.out.println("start collect");
        System.gc( );
        System.out.println("end collect");
        Thread.sleep(1000);
        System.out.println("end program");
    }
    
    private static class NoisyButton extends JButton {
        private static final long serialVersionUID = 1L;
        private final String name;
    
        public NoisyButton(String name) {
            super();
            this.name = name;
        }
    
        @Override
        protected void finalize() throws Throwable {
            System.out.println(name + " finalized");
            super.finalize();
        }
    }
    }
    

    produces:

    start collect
    end collect
    first finalized
    second finalized
    end program
    

提交回复
热议问题