2

Doesn't this cause a memory leak because now you cannot remove the action listener when the attacher is getting collected?

this.btnClickMe.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.append("Hello\n");
            }
        });

Wouldn't it instead be better to do this?

this.clickMeButtonActionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.append("Hello\n");
            }
        };

 this.btnClickMe.addActionListener(this.clickMeButtonActionListener);

...

@Override
public void dispose() {

    this.btnClickMe.removeActionListener(
               this.clickMeButtonActionListener);

    super.dispose();
}
Water Cooler v2
  • 32,724
  • 54
  • 166
  • 336

2 Answers2

2

No.

You don't need to implement dispose and generally never should.

Your anonymous listener will be garbage collected like everything else when btnClickMe is disposed of and no more references to it exist, without you having to do anything.

If the listener is temporary then sure, store it then remove it when you're done with it logically with removeActionListener. But not in dispose, you don't even know when or if dispose will be called. Do it when your application no longer needs the listener attached.

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • Thank you. What's the place to write any sort of farewell code when a `JFrame` or `JDialog` in Swing is closing? – Water Cooler v2 Aug 26 '16 at 03:58
  • @Water Nowhere, ideally. Close it, then discard any references you have to it by e.g. `thatJFrame = null`, and let the GC do the dirty work for all its members and their members and so on. Note that the GC can deal with circular references just fine. – Jason C Aug 26 '16 at 03:59
0

Your question is a good example that "half-knowledge" is actually a dangerous thing.

It seems that you understand that Java is garbage collected; but on the other hand - you are missing the understanding how that really works.

So, in short: objects are alive as long as they can be reached when looking at the heap. An anonymous listener is only alive as long as its "owner" is alive. Thus: when your frame/panel ... goes out of existence, all owned listeners "die" with it, too. Thus they become eligible for garbage collection.

GhostCat
  • 137,827
  • 25
  • 176
  • 248