Weak array


In programming languages, a weak array refers to an array that contains only weak references or weak pointers. As such, the references contained within these arrays do not protect the referenced objects from garbage collection. This type of array is defined in contrast to a typical (strong) array, which contains references which prevent the referenced objects from garbage collection until the reference itself is garbage collected.

The garbage collector replaces a pointer in the weak array with the null pointer if it discovers that no strong pointer points to the same object.[1]

Uses

One of the most common uses for weak arrays is in a data sink model. If a data source is feeding into many sinks, it may be the case that some sinks become redundant over time. If the data source is maintaining a set of strong references to the sinks, none of the redundant sinks can be garbage collected due to the strong nature of the pointers held to them from the source. The problem becomes more severe if the data source is permanent, all sinks referenced by the source in this model may never be removed by the garbage collector due to the permanent strong references in the data source.

If the same model is used with the data source maintaining a weak array of data sink references, any redundant sinks could be collected as and when they are no longer in use, even if the weak pointers in the source are held indefinitely. This allows systems to be much more efficient over their lifetime without changing their structure or adding explicit management code.

References