Skip to content
Antonio Vieiro edited this page Jan 25, 2018 · 1 revision

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.

Apache Migration Information

The content in this page was kindly donated by Oracle Corp. to the Apache Software Foundation.

This page was exported from http://wiki.netbeans.org/DevFaqWeakListener , that was last modified by NetBeans user Tboudreau on 2010-01-24T06:12:27Z.

NOTE: This document was automatically converted to the AsciiDoc format on 2018-01-26, and needs to be reviewed.

Clone this wiki locally