Weak reference
   HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, a weak reference is a
reference Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
that does not protect the referenced
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
from collection by a
garbage collector A waste collector, also known as a garbageman, garbage collector, trashman (in the US), binman or (rarely) dustman (in the UK), is a person employed by a public or private enterprise to collect and dispose of municipal solid waste (refuse) and ...
, 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 In computer programming, unreachable memory is a block of dynamically allocated memory where the program that allocated the memory no longer has any reachable pointer that refers to it. Similarly, an unreachable object is a dynamically allo ...
,'' 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 C#,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
,
Lisp A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech. Types * A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lispin ...
,
OCaml OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. ...
,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, Python and PHP since the version 7.4.


Uses

Weak references have a number of common uses. When using
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
garbage collection, weak references can break
reference cycle In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, referen ...
s, by using a weak reference for a link in the cycle. When one has an
associative array In computer science, an associative array, map, symbol table, or dictionary is an abstract data type that stores a collection of (key, value) pairs, such that each possible key appears at most once in the collection. In mathematical terms an ...
(mapping, hash map) whose keys are (references to) objects, for example to hold auxiliary data about objects, using weak references for the keys avoids keeping the objects alive just because of their use as keys. When one has an object where other objects are registered, such as in the
observer pattern In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by ca ...
(particularly in
event handling In programming and software design, an event is an action or occurrence recognized by software, often originating asynchronously from the external environment, that may be handled by the software. Computer events can be generated or triggered ...
), if a strong reference is kept, objects must be explicitly unregistered, otherwise a memory leak occurs (the
lapsed listener problem In computer programming, the lapsed listener problem is a common source of memory leaks for object-oriented programming languages, among the most common ones for garbage collected languages.container A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping. Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
whose keys or values are weak references.


Garbage collection

Garbage collection is used to clean up unused objects and so reduce the potential for
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object ...
s and data corruption. There are two main types of garbage collection: tracing and
reference counting In computer science, reference counting is a programming technique of storing the number of references, pointers, or handles to a resource, such as an object, a block of memory, disk space, and others. In garbage collection algorithms, refer ...
. Reference counting schemes record the number of references to a given object and collect the object when the reference count becomes zero. Reference-counting cannot collect cyclic (or circular) references because only one object may be collected at a time. Groups of mutually referencing objects which are not directly referenced by other objects and are unreachable can thus become permanently resident; if an application continually generates such unreachable groups of unreachable objects this will have the effect of a
memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object ...
. Weak references (references which are not counted in reference counting) may be used to solve the problem of circular references if the reference cycles are avoided by using weak references for some of the references within the group. A very common case of such strong vs. weak reference distinctions is in tree structures, such as the
Document Object Model The Document Object Model (DOM) is a cross-platform and language-independent interface that treats an XML or HTML document as a tree structure wherein each node is an object representing a part of the document. The DOM represents a document wi ...
(DOM), where parent-to-child references are strong, but child-to-parent references are weak. For example, Apple's
Cocoa Cocoa may refer to: Chocolate * Chocolate * ''Theobroma cacao'', the cocoa tree * Cocoa bean, seed of ''Theobroma cacao'' * Chocolate liquor, or cocoa liquor, pure, liquid chocolate extracted from the cocoa bean, including both cocoa butter an ...
framework recommends this approach. Indeed, even when the object graph is not a tree, a tree structure can often be imposed by the notion of object ownership, where ownership relationships are strong and form a tree, and non-ownership relationships are weak and not needed to form the tree – this approach is common in
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
(pre-C++11), using raw pointers as weak references. This approach, however, has the downside of not allowing the ability to detect when a parent branch has been removed and deleted. Since the
C++11 C11, C.XI, C-11 or C.11 may refer to: Transport * C-11 Fleetster, a 1920s American light transport aircraft for use of the United States Assistant Secretary of War * Fokker C.XI, a 1935 Dutch reconnaissance seaplane * LET C-11, a license-build ...
standard, a solution was added by using shared ptr and weak ptr, inherited from the Boost library. Weak references are also used to minimize the number of unnecessary objects in memory by allowing the program to indicate which objects are of minor importance by only weakly referencing them.


Variations

Some languages have multiple levels of weak reference strength. For example,
Java Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
has, in order of decreasing strength, soft, weak, and
phantom Phantom may refer to: * Spirit (animating force), the vital principle or animating force within all living things ** Ghost, the soul or spirit of a dead person or animal that can appear to the living Aircraft * Boeing Phantom Ray, a stealthy unm ...
references, defined in the package java.lang.ref. Each reference type has an associated notion of reachability. The garbage collector (GC) uses an object's type of reachability to determine when to free the object. It is safe for the GC to free an object that is softly reachable, but the GC may decide not to do so if it believes the JVM can spare the memory (e.g. the JVM has much unused heap space). The GC will free a weakly reachable object as soon as the GC notices the object. Unlike the other reference types, a phantom reference cannot be followed. On the other hand, phantom references provide a mechanism to notify the program when an object has been freed (notification is implemented using ReferenceQueues). In C#, weak references are distinguished by whether they track
object resurrection In object-oriented programming languages with garbage collection, object resurrection is when an object comes back to life during the process of object destruction, as a side effect of a finalizer being executed. Object resurrection causes a n ...
or not. This distinction does not occur for strong references, as objects are not finalized if they have any strong references to them. By default, in C# weak reference do not track resurrection, meaning a weak reference is not updated if an object is resurrected; these are called short weak references, and weak references that track resurrection are called long weak references. Some non-garbage-collected languages, such as
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, provide weak/strong reference functionality as part of supporting garbage collection libraries. The Boost C++ library provides strong and weak references. It is a mistake to use regular C++ pointers as the ''weak'' counterparts of smart pointers because such usage removes the ability to detect when the ''strong'' reference count has gone to 0 and the object has been deleted. Worse yet, it doesn't allow for detection of whether another strong reference is already tracking a given plain pointer. This introduces the possibility of having two (or more) smart pointers tracking the same plain pointer (which causes corruption as soon as one of these smart pointers' reference count reaches 0 and the object gets deleted).


Examples

Weak references can be useful when keeping a list 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 for the duration of the program.


Java

Java 1.2 in 1998 introduced two kinds of weak references, one known as a “soft reference” (intended to be used for maintaining GC-managed in-memory caches, but which doesn’t work very well in practice on some platforms with dynamic heap like Android) and the other simply as a “weak reference”. It also added a related experimental mechanism dubbed “phantom references” as an alternative to the dangerous and inefficient finalize() mechanism. If a weak reference is created, and then elsewhere in the code get() is used to get the actual object, the weak reference isn't strong enough to prevent garbage collection, so it may be (if there are no strong references to the object) that get() suddenly starts returning null.https://web.archive.org/web/20110303225354/http://weblogs.java.net/blog/2006/05/04/understanding-weak-references Java Examples import java.lang.ref.WeakReference; public class ReferenceTest Another use of weak references is in writing a
cache Cache, caching, or caché may refer to: Places United States * Cache, Idaho, an unincorporated community * Cache, Illinois, an unincorporated community * Cache, Oklahoma, a city in Comanche County * Cache, Utah, Cache County, Utah * Cache County ...
. Using, for example, a weak hash map, one can store in the cache the various referred objects via a weak reference. When the garbage collector runs — when for example the application's memory usage gets sufficiently high — those cached objects which are no longer directly referenced by other objects are removed from the cache.


Smalltalk

, a s1 s2, s1 := 'hello' copy. "that's a strong reference" s2 := 'world' copy. "that's a strong reference" a := WeakArray with:s1 with:s2. a printOn: Transcript. ObjectMemory collectGarbage. a printOn: Transcript. "both elements still there" s1 := nil. "strong reference goes away" ObjectMemory collectGarbage. a printOn: Transcript. "first element gone" s2 := nil. "strong reference goes away" ObjectMemory collectGarbage. a printOn: Transcript. "second element gone"


Lua

weak_table = setmetatable(, ) weak_table.item = print(weak_table.item) collectgarbage() print(weak_table.item)


Objective-C 2.0

In
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXT ...
2.0, not only garbage collection, but also
automatic reference counting Automatic Reference Counting (ARC) is a memory management feature of the Clang compiler providing automatic reference counting for the Objective-C and Swift programming languages. At compile time, it inserts into the object code messages retain a ...
will be affected by weak references. All variables and properties in the following example are weak. @interface WeakRef : NSObject @property (nonatomic, weak) NSString *str3; @property (nonatomic, unsafe_unretained) NSString *str4; @end The difference between weak (__weak) and unsafe_unretained (__unsafe_unretained) is that when the object the variable pointed to is being deallocated, whether the value of the variable is going to be changed or not. weak ones will be updated to nil and the unsafe_unretained one will be left unchanged, as a dangling pointer. The weak references is added to Objective-C since Mac OS X 10.7 "Lion" and iOS 5, together with
Xcode Xcode is Apple's integrated development environment (IDE) for macOS, used to develop software for macOS, iOS, iPadOS, watchOS, and tvOS. It was initially released in late 2003; the latest stable release is version 14.2, released on December 13, ...
4.1 (4.2 for iOS), and only when using ARC. Older versions of Mac OS X, iOS, and GNUstep support only unsafe_unretained references as weak ones.


Vala Vala or VALA may refer to: Religion and mythology * Vala (Vedic), a demon or a stone cavern in the Hindu scriptures * Völva, also spelled Vala, a priestess in Norse mythology and Norse paganism Fiction * Vala (Middle-earth), an angelic being in ...

class Node


Python

>>> import weakref >>> import gc >>> class Egg: ... def spam(self): ... print("I'm alive!") ... >>> obj = Egg() >>> weak_obj = weakref.ref(obj) >>> weak_obj().spam() I'm alive! >>> obj = "Something else" >>> gc.collect() 35 >>> weak_obj().spam() Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'spam'


See also

*
Soft reference A soft reference is a reference that is garbage-collected less aggressively. The soft reference is one of the strengths or levels of 'non strong' reference defined in the Java programming language, the others being weak and phantom. In order from ...
*
Phantom reference A phantom reference is a kind of reference in Java, where the memory can be reclaimed. The phantom reference is one of the strengths or levels of 'non strong' reference defined in the Java programming language; the others being weak and soft. P ...
*
Circular reference A circular reference is a series of references where the last object references the first, resulting in a closed loop. In language A circular reference is not to be confused with the logical fallacy of a circular argument. Although a circula ...
* Ephemeron


References

*


External links


C++

* C++11 Standard Library
std::weak_ptr reference
* Boost 1.59 (C++ library)
boost::weak_ptr reference


Java


Java developer article: 'Reference Objects and Garbage Collection'
*
RCache - Java Library for weak/soft reference based cache

Java theory and practice: Plugging memory leaks with weak references


PHP


Weak References


Python



* Fred L. Drake, Jr.,
PEP 205: Weak References
', Python Enhancement Proposal, January 2001. {{DEFAULTSORT:Weak Reference Data types Memory management