Java reference objects: strong, soft, weak, and phantom

Java reference objects: strong, soft, weak, and phantom

Java reference objects generally provide two ways of interaction with the garbage collector: to control when an object can be garbage collected and to receive a notification when an object is garbage collected. After so long, I find myself not able to clearly describe them again. I would like to take some notes here as my memory was just refreshed, in case I forget later. This is going to be a short note, just enough for distinguishing them by their most prominent characteristics. Please consult the javadoc for more details.

Without any reference object used, the references through equal signs are strong ones, which are also the regular references we use most of the time. Objects being strongly referenced are not reclaimed by the garbage collector even though a java.lang.OutOfMemoryError is about to be thrown.

The immediate weaker references than strong ones are soft references. Objects being softly referenced through SoftReference without stronger references may survive garbage collections at the discretion of the garbage collector, but they are guaranteed to be reclaimed before a java.lang.OutOfMemoryError is thrown. Soft references are cleared by the garbage collector automatically, so there is no need to call SoftReference#clear() explicitly. When an object being softly referenced is reclaimed, its SoftReference object is enqueued to a ReferenceQueue if registered through the constructor. You may want to subclass SoftReference to carry more information.

The immediate weaker references than soft ones are weak references. Objects being weakly referenced through WeakReference without stronger references cannot survive garbage collections. Weak references are cleared automatically and enqueued like soft references. Using weak references to implement caching may not be very effective, since cached data can only live as long as the intervals between two garbage collections. After all, weak references are not intended for this purpose.

While phantom references are considered to be the weakest, they mainly serve the purpose of receiving notifications through ReferenceQueues. This notification mechanism may work in synergy with the finalization mechanism in that objects being referenced only through PhantomReference have already been finalized. Note that phantom references are not cleared automatically, so PhantomReference#clear() must be called explicitly or the PhantomReference object itself must become reclaimable.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

To prevent automated spam submissions leave this field empty.