What types of references exist in Java?

In addition to the regular strong reference to an object, there are types of references that are handled differently by the garbage collector. These are subclasses of java.lang.ref.Reference. They all implement various forms of weak references. Technically, they are wrappers around an object that is accessible via the get() method and can be garbage collected while the reference wrapper still exists. They are used to save memory, implement caches, and handle external resource finalization. For example, in Android, weak references are sometimes used to prevent Activity leaks.

Here are the types of references, in order of decreasing "strength":
  • Regular strong reference – Any variable of a reference type. The object will not be garbage collected until it becomes unused (i.e., it is no longer accessible from the GC roots, more on this in future posts).
  • SoftReference – The object won’t cause memory exhaustion - it is guaranteed to be removed before OutOfMemoryError occurs. It may be collected earlier, depending on the garbage collector’s implementation.
  • WeakReference – Weaker than a soft reference. It does not prevent the object from being garbage collected, as the garbage collector ignores such references.
  • PhantomReference – Used for "post-mortem" processing of an object: the object is available after finalization but before it is cleared by the garbage collector.
You can read more in this article and, as usual, in the class documentation.