Alex Rivera | Logout

Is there a practical use for weak references?

Asked 2012-01-09T15:09:07.763
102

Possible Duplicate:
Weak references - how useful are they?

Since weak references can be claimed by the garbage collector at any time, is there any practical reason for using them?

Edit
Report

2 Answers

3

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 avoid keeping memory referenced by unneeded objects. Some garbage-collected languages feature or support various levels of weak references, such as Java, C#, Python, Perl, PHP or Lisp.
  • Garbage collection is used to 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 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.
  • 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.
answered 2012-01-09T15:33:52.823
2

I use it generally for some type of cache. Recently accessed items are available immediately and in the case of cache miss you reload the item (DB, FS, whatever).

answered 2012-01-09T16:06:19.647

Your Answer