DevFaqWeakListener

What is a WeakListener

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.

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo