In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time. Some garbage-collected languages feature or support various levels of weak references, such as Java, C#, Python,Perl, and Lisp.
Weak references have a number of common use cases. When using reference counting garbage collection, weak references can break reference cycles, by using a weak reference for a link in the cycle. When one has an associative array (mapping, hash map) whose keys are (references to) objects, for example to hold auxiliary value about objects, using weak references for the keys avoids keeping the objects alive just because of their use as a key. When one has an object where other objects are registered, such as in the observer pattern (particularly in event handling), if a strong reference is kept, objects must be explicitly unregistered, otherwise a memory leak occurs (the lapsed listener problem), while a weak reference removes the need to unregister. When holding cached data that can be recreated if necessary, weak references allow the cache to be reclaimed, effectively producing discardable memory. This last case (a cache) is distinct from others, as it is preferable that the objects only be garbage collected if necessary, and there is thus a need for finer distinctions within weak references, here a stronger form of a weak reference. In many cases weak references do not need to be directly used, instead simply using a weak array or other container whose keys or values are weak references.