Pattern: Weak Collections


Context

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 there are occasions when you want to hold a collection of objects without increasing their reference counts.

Solution

Weak collections hold elements without increasing their reference counts. The following types of weak collection are available.

Example

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 WeakSet now only contains 'aStringWithAReference'."

Consequences

Objects will disappear from a weak collection when there are no other references.

Known Uses

The dependency mechanism uses a WeakIdentityDictionary to hold references to the dependents without affecting the way that they are garbage collected.