Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I obliged to call removeMouseListener()?

If I have added a MouseListener using Component#addMouseListener() am I obliged to remove it using removeMouseListener()?

I'm thinking particularly in terms of memory leaks of the kind that javax.swing.Timer can cause if stop() is not called.

I can't find anything in the documentation to say that listeners should be removed, but I'm maybe thinking that this is something that might be assumed by the writer. Perhaps.

Inspecting the JDK source suggests that in the absence of references in the mouse listeners themselves that would prevent it, the presence of a listener will not prevent an eligible component from being GC'd.

I guess, given the maxim "it's better safe than sorry", I'm really asking if anyone can point me to some documentation that indicates that it is not obligatory to remove either mouse listeners, or the more general case of any listener.

like image 758
clstrfsck Avatar asked Mar 09 '11 01:03

clstrfsck


2 Answers

It depends on what other objects are holding references to the listener, and whether or not the listener has a reference to the component. I've looked into the Swing code a bit and, as best I can tell, listener registrations hold strong references to their listeners.

If you created a new listener in your call to addMouseListener, such as addMouseListener(new MouseListener()...) then you should be okay without explicitly unregistering the listener. When the garbage collector checks the component, that listener is not strongly-reachable outside the component, so it won't prevent the garbage collector from reclaiming the component.

However, if you have something like this:

public class Foo implements MouseListener {
    ...
    private Component c;
    public void registerWithComponent(final Component c) {
        c.addMouseListener(this);
        this.c = c;
    }
}

then the component can't be reclaimed by the garbage collector until your Foo instance is also reclaimed (or can be reclaimed), and you probably should make an explicit call to removeMouseListener.

like image 121
sworisbreathing Avatar answered Oct 17 '22 21:10

sworisbreathing


You don't remove them unless you no longer want that behavior.

The GC in Java cleans up any objects with no remaining references (e.g. the Component is GC'd and you aren't holding a reference to the MouseListener somewhere else)

like image 1
Brian Roach Avatar answered Oct 17 '22 22:10

Brian Roach