Background
So I read that often memory leaks within Swing applications originate from the use of various listeners (mouse, key, focus, etc). Essentially, you register an object as a listener and forget to deregister the object, the notifier ends up holding onto the reference of the object, leaking a bit of memory.
I knew our application wasn't deregistering listeners and did a bit of research on potential solutions:
I found one approach in dealing with the problem was the use of a WeakReference, full details on the approach with swing listeners can be found here.
I then became curious about how the NetBeans form editor was generating code to clean up after listeners added to the form and discovered that NetBeans was registering listeners via a wrapping object i.e.
argTypeComboBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
argTypeComboBoxItemStateChanged(evt);
}
});
But the generated code did not seem to ever clean up by calling removeItemListener.
Questions
Is the wrapping object acting like a weak reference? To me it looks like it could leak a tiny amount of memory (the size of the wrapping object)?
Do you have alternative approaches when dealing with listeners to ensure that they are always garbage collected when you are finished with them?