title: How to resolve swing listener memory leaks?
body: <p><strong>Background</strong></p>
  
  <p>So I read that often memory leaks within Swing applications originate from the use of various listeners (mouse, key, focus, etc). Essentially, because you register an object as a listener and forget to deregister the object, the notifier ends up holding onto the reference of the object, and leaks a bit of memory.</p>
  
  <p>I knew our application wasn't deregistering listeners and did a bit of research on potential solutions:</p>
  
  <p>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 <a href="http://www.javalobby.org/java/forums/t19468.html" rel="nofollow noreferrer">here</a>.</p>
  
  <p>I then became curious about how the <a href="http://netbeans.org/" rel="nofollow noreferrer">NetBeans</a> 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.</p>
  
  <pre><code>argTypeComboBox.addItemListener(new java.awt.event.ItemListener() {
      public void itemStateChanged(java.awt.event.ItemEvent evt) {
        argTypeComboBoxItemStateChanged(evt);
      }
  });
  </code></pre>
  
  <p>But the generated code did not seem to ever clean up by calling <code>removeItemListener</code>.</p>
  
  <p><strong>Questions</strong></p>
  
  <p>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)?</p>
  
  <p>Do you have alternative approaches when dealing with listeners to ensure that they are always garbage collected when you are finished with them?</p>