When using an anonymous inner class as a PropertyChangeListener at what point in the object life cycle is the class garbage collected? After the containing class (SettingsNode) is reclaimed? Should I explicitly remove the PropertyChangeListener in the finalizer of the containing class (SettingsNode)?
public class SettingsNode extends AbstractNode
{
public SettingsNode(Project project, ProjectSettings projectSettings)
throws IntrospectionException
{
// use an anonymous inner class to listen for changes
projectSettings.addPropertyChangeListener(ProjectSettings.PROP_NAME,
new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
// handle event
}
});
}
}
Like all objects, the anonymous inner class is eligible for garbage collected when the last reference to it no longer references it. I’m using weasel wording here because Java doesn’t guarantee that things will be GC’d – the only guarantee is that it won’t happen as long as there is a reference.
In this particular case, that would be when
projectSettingseither does aremovePropertyListener()or is itself garbage collected.Because
projectSettingsreferences the anonymous inner class and because the inner class references its containing class, that means the containing class will also live at least as long as the inner class.