public abstract class IlvAbstractWeakEventListener extends Object
The typical use case: a listener gets installed at an source object. The listener is needed as long as a reference target object exists, but there is no notification when the reference target object disappears. The problem is to deinstall the listener from the source object to avoid memory leaks.
Let's put the use case more concrete:
An application has a javax.swing.Action
that might get
triggered from various Swing buttons. The swing buttons need to install
a property change listener at the action to be informed when the action
is enabled etc. Lets assume new buttons for the action are created over
time (e.g. when opening documents), and old buttons of the action
disappear (e.g. when closing documents). When a button disappears, it
should remove the property change listener from the action to avoid
memory leaks, but if there is no callback method that allows to do this
cleanup, it is difficult to solve. In this case, the
solution is to create an IlvAbstractWeakEventListener
which makes sure the property change listener is removed automatically
some time after the button was garbage collected. Example code:
class ButtonPropertyChangeListener extends IlvAbstractWeakEventListener implements PropertyChangeListener { ButtonPropertyChangeListener(Action action, JComponent button) { super(action, button); action.addPropertyChangeListener(this); } protected void cleanup(Object action) { ((Action)action).removePropertyChangeListener(this); } public void propertyChange(PropertyChangeEvent evt) { ... } }
Constructor and Description |
---|
IlvAbstractWeakEventListener(Object source,
Object target)
Creates a new weak event listener.
|
Modifier and Type | Method and Description |
---|---|
protected abstract void |
cleanup(Object source)
Cleans when the target gets garbage collected.
|
Object |
getSource()
Returns the source of the listener.
|
Object |
getTarget()
Returns the target of the listener.
|
void |
setTarget(Object target)
Sets the target of the listener.
|
public IlvAbstractWeakEventListener(Object source, Object target)
source
- The source object the listener should be added to.target
- The target object that needs the listener. The goal is that
the listener is removed from the source object when the
target object is scheduled for garbage collection.public Object getSource()
public Object getTarget()
null
if the target is already garbage collected.public void setTarget(Object target)
cleanup(java.lang.Object)
is eventually called.protected abstract void cleanup(Object source)
cleanup
is not called. Some time after the target got garbage collected,
cleanup
is called, but the exact time point is undefined.source
- The source object the listener should be removed from.getTarget()
© Copyright Rogue Wave Software, Inc. 1997, 2018. All Rights Reserved.