Weak reference

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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 is considered unreachable (or "weakly reachable") 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.

Contents

[edit] Garbage collection

Garbage collection is used to clean up unused objects and so reduce the potential for memory leaks and data corruption. There are two main types of garbage collection: tracing and reference counting. 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. 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. For example, Apple's Cocoa framework recommends this approach, by using strong references for "parent-to-child" references, and weak references for "child-to-parent" references, thus avoiding cycles.[1]

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.

[edit] Variations

Some languages have multiple levels of weak reference strength. For example, Java has — in order of decreasing strength — soft, weak, and phantom references, defined in the package java.lang.ref.[1] 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 lots of 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).

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

[edit] Examples

Weak references can be useful in 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).

[edit] Java Example

If you create a weak reference and then elsewhere in the code you can use get() to get the actual object, the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the object) that get() suddenly starts returning null.[2]

import java.lang.ref.WeakReference;
 
public class ReferenceTest {
        public static void main(String[] args) throws InterruptedException {
 
                Student s1 = new Student(1);
                System.out.println(s1);
                WeakReference<Student> ws = new WeakReference<Student>(s1);
                System.out.println(ws.get());
                s1 = null;
                System.gc();
                Thread.sleep(1000);
 
                System.out.println(ws.get());
        }
}
 
class Student {
        public Student(int id) {
                this.id = id;
        }
 
        int id;
 
        public String toString() {
 
                return "[id=" + id + "]";
 
        }
}

Another use of weak references is in writing a cache. 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.

[edit] Lua Example

weak_table = setmetatable({}, {__mode="v"})
weak_table.item = {}
print(weak_table.item)
collectgarbage()
print(weak_table.item)

[edit] See also

[edit] Notes

  1. ^ Nicholas, Ethan. "Understanding Weak References". java.net. published on May 4, 2006. accessed on October 1, 2010
  2. ^ weblogs.java.net Java Examples

[edit] External links

Personal tools
Namespaces
Variants
Actions
Navigation
Interaction
Toolbox
Print/export
Languages