Cook Computing

Weak References

June 20, 2002 Written by Charles Cook

Funny how you miss things sometimes. It was only when reading Richard Grimes' book last night that I came across weak references. His example is:


class C
{
 private WeakReference b = null;

 public C (B bref)
 {
  b = new WeakReference(bref);
 }

 public void UseB()
 {
  if (b.IsAlive)
  {
   B bref = (B)b.Target;
   // use bref
  }
 }
}

While an instance of C holds a weak reference to instance of B in the b member, the garbage collector can destroy the object. UseB checks whether the object still exists by calling the IsAlive method of the WeakReference and then calls the Target method of the WeakReference to obtain a normal strong reference to the object(or simply checks if the result of the Target call is null before using it).

Weak references are used for memory usage optimizations. For example if a large object may be needed again but its ok to destroy it if memory runs short and recreate it when required again, it can be held via a weak reference. If the GC runs, the object is destroyed, otherwise it remains available for further use.

Richter describes weak references in this article.