Weak reference

From Wikipedia, the free encyclopedia

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, Python and ActionScript 3.0.

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 defined in the Java package java.lang.ref. 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" (although pointers are not true weak references, as weak references are supposed to know when the object becomes unreachable).

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).

In other languages