Weak reference
|
In computer programming, a weak reference is a reference that does not protect the referent object from collection by a garbage collector. An object referenced only by weak references is considered unreachable (or "weakly reachable") and so may be collected at any time. Weak references are used to prevent circular references and to avoid keeping in memory referenced but unneeded objects. Many garbage-collected, object-oriented languages feature weak references, such as Java and Python.
Garbage collection (GC) is used to reduce the potential for memory leaks and data corruption. There are two main types of GC - tracing GC and reference counting GC. Reference counting schemes record the number of references to a given object and collect the object when the reference count becomes zero. Reference-counting GC cannot collect cyclic (or circular) references because only one object may be collected at a time. Groups of mutually referencing objects can thus become effective memory leaks. Weak references may be used to solve the problem of circular references if the reference cycles are broken by replacing strong references with weak references.
Weak references are also used to minimize the number of unnecessary objects in memory by allowing the program to indicate which objects are not critical by only weakly referencing them.
Some languages have multiple levels of weak reference strength. For example, Java has weak, phantom and soft references. Some non-garbage-collected languages, such as C++, provide weak/strong reference functionality as part of supporting garbage collection libraries. In the case of C++, normal pointers are "weak" and smart pointers are "strong".
One example of how a weak reference can be useful is keeping track of the current variables being referenced in the application. This list must have weak links to the objects. Otherwise, once objects are added to the list, they will be referenced by it and will persist forever (or until the program stops).