What is a WeakListener ?

Apache NetBeans Wiki Index

Note: These pages are being reviewed.

When you attach a listener to another object, via, for example, an addPropertyChangeListener() method, that other object now holds a reference to that listener.

In Java, any object that is referenced by another object which is still in use (i.e. referenced by something else that is still alive, and so forth) cannot be garbage collected. One of the most frequent sources of memory leaks in Swing applications is attaching a listener to some long-lived object and never detaching the listener. The entire object graph of the listener and anything it references is held in memory, whether it is needed or not, until the object being listened to is finally garbage collected.

Since listeners are often implemented as inner (non-static) classes of some other object, and an inner class keeps a reference to the object that created it, the outer object instance is kept in memory too.

WeakListeners is a factory class which wraps your event listener in another one, but it only weakly (using java.lang.ref.WeakReference) references your actual listener. That means that, even though you are listening for changes, that will not block your listener from being garbage collected if nothing else still references it.

There is one caveat to using WeakListeners - if you do something like this:

someObject.addPropertyChangeListener(WeakListeners.propertyChange(new PropertyChangeListener() {
   public void propertyChange(PropertyChangeEvent evt) {
     ...
   }
}, someObject);

in fact you are not listening on someObject for any amount of time - the anonymous PropertyChangeListener you created will be instantly garbage-collected. So keep a reference to your listener when using WeakListeners.