Reputation: 33850
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();
}
Upvotes: 2
Views: 191
Reputation: 140457
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.
Upvotes: 0
Reputation: 40335
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.
Upvotes: 2