Gangmax Blog

自由之思想,独立之精神

Understanding Java Weak References

| Comments

From here.

First, a normal strong reference will make the pointed object cannot be GCed.

However in some cases, we want to trace some objects but don’t want the tracing action itself makes the objects cannot be GCed, that is where the weak references should be used.

The following classes help to explain the concepts:

  1. ReferenceQueue

    When the object which is pointed by a WeakReference bacomes garbage, the WeakReference instance itself should be GCed too. In order to do so, ReferenceQueue should be used, which will contain the invalid WeakReference instance when the pointed object bacome garbage if you use the ReferenceQueue instance in the WeakReference’s constructor. Then you can clean up the ReferenceQueue at some regular interval.

  2. WeakReference

    As explained above.

  3. SoftReference

    Similar to WeakReference. Except that, if an object is only pointed by a WeakReference, it will be GCed immediately in the next GC round(minor GC?); however if an object is pointed by a SoftReference only, it won’t be GCed immediately until the JVM has some reason that has to do it, such as insufficient memory(full GC?). Caching is a typical scenario to use SoftReference.

  4. PhantomReference

    No like “WeakReference” and “SoftReference”. The only use for such a reference is keeping track of when it gets enqueued into a ReferenceQueue.

Comments