Navigation: Appendix B: Dolphin Pattern Book > Object Lifetime Patterns >
Objects are garbage collected if there are no references to them. Holding an object in a collection will increase its reference count and stop it from being garbage collected, even if there are no other references to that object. This is normally the desired behaviour, but on the occasions when you want to hold a collection of objects without increasing their reference counts, how can this be achieved.
Use Weak Collections to hold elements without increasing their reference counts. The following weak collection classes are available.
Try the following:
Smalltalk at: #S put: 'aStringWithAReference'.
Smalltalk at: #WeakSetTest put: WeakSet new.
WeakSetTest add: S.
WeakSetTest add: 'aStringWithNoReferences'.
WeakSetTest size. "This should evaluate to 2."
"Wait a few seconds for the next garbage collection to occur."
WeakSetTest size. "This should evaluate to 1."
The weak set, S, now only contains 'aStringWithAReference'
Objects will disappear from a weak collection when there are no other references.
The dependency mechanism uses a WeakIdentityDictionary to hold references to the dependents without affecting the way that they are garbage collected.