It seems to me, that I found a situation, when the standard garbage collection algorithm can't be used well.
Suppose I have some object A
, which adds itself as event listener for events from object B
upon construction. Since object has all required data to add itself as a listener, hence it also has data to remove itself from listeners.
Unfortunately, the removal process can't be initiated by GC
, because object will be referenced in listeners list until explicitly removed.
So, this means that either object should never add itself as a listener, or there should be a way to mark some references as unimportant. In latter case GC
would initiate garbage collection even if some references to the object exist -- if they are only of "unimportant" case.
Obviously, programmer should be obliged to clear all unimportant references in some method like dispose
or finalize
.
I understand that this direct implementation would be a security bleach. For example, if programmer violated disposing contract, garbage collection would provide incorrect references.
So, the question is: is there some library or pattern, to implement this relationship?
If you just want your object lifetime to be managed to references to it other than as a listener then you could change your collection of listeners to be a 'Weak' collection like WeakHashMap. Such a collection uses Weak References to avoid keeping objects alive after all other references have been cleared.