Skip to content
Tutorials Center
My learning

Topics

Lesson 152 of 201 ยท JVM and Advanced Topics

Soft, Weak and Phantom References

Learn Java reference types - strong, soft, weak and phantom references, ReferenceQueue, WeakHashMap and Cleaner - with runnable examples and cache guidance.

In Memory and Garbage Collection you learned the rule of the collector: an object stays alive as long as it is reachable through references. Ordinary variables, fields and collection elements are strong references, and one strong path is enough to keep an object forever. That is usually what you want, but sometimes you would like to say "keep this if there is room, but do not prevent its collection", or "tell me when this object is gone".

The java.lang.ref package provides exactly that with three more kinds of reference: soft, weak and phantom. They are the foundation of caches that do not cause memory leaks, of WeakHashMap, and of Cleaner, the modern way to release native resources. Used carelessly they cause confusing bugs, so this lesson also covers when not to use them.

The four strengths

Reachability has four levels, from strongest to weakest. The collector looks at the strongest path to an object when deciding its fate:

Reference Class Cleared when Typical use
Strong any variable never while reachable everything
Soft SoftReference<T> the JVM needs memory (before OutOfMemoryError) memory-sensitive caches
Weak WeakReference<T> at the next GC after no strong/soft path remains canonical maps, listeners, WeakHashMap
Phantom PhantomReference<T> after the object is finalizable; get() always returns null cleanup actions

A reference object is a small wrapper around its referent. You create it with the referent and read it back with get(), which returns null once the referent has been collected. Because get() can turn null at any moment, you must copy the result into a local variable and test that variable:

Java
Blob blob = ref.get();      // now a strong reference again
if (blob != null) {
    use(blob);              // safe: the local variable keeps it alive
}

Writing if (ref.get() != null) { ref.get().use(); } is a classic bug, because the object can vanish between the two calls.

Soft and weak references in action

This example creates one object of each kind and runs the collector. Remember that System.gc() is only a request, but on our server's JVM it reliably performs a full collection, so it is useful for experiments (never call it in production code):

Java What survives a garbage collection?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The weakly referenced blob is gone after one collection, while the softly referenced one is still there: a soft reference survives while the heap has room. The weakOfStrong reference still returns its object because the local variable strong is a strong path. Weak references never keep an object alive; they merely let you look at it while someone else does. clear() empties a reference manually, and after it get() returns null even for a live referent.

Soft references as a cache

A SoftReference is meant for caches: values that are expensive to rebuild but not essential. If memory gets tight, the JVM clears soft references before it throws OutOfMemoryError, so a soft cache cannot cause that error by itself. A simple version looks like this:

Java
class ImageCache {
    private final Map<String, SoftReference<byte[]>> cache = new ConcurrentHashMap<>();

    byte[] load(String name) {
        SoftReference<byte[]> ref = cache.get(name);
        byte[] data = (ref == null) ? null : ref.get();
        if (data == null) {
            data = readFromDisk(name);                    // expensive
            cache.put(name, new SoftReference<>(data));
        }
        return data;
    }
}

The HotSpot JVM decides how long to keep soft references by a time-based policy: roughly one second of idle time per megabyte of free heap (-XX:SoftRefLRUPolicyMSPerMB, default 1000). That makes the behavior hard to predict, and it is why many teams prefer an explicit size-bounded cache with an eviction policy, such as a LinkedHashMap in access order or a library like Caffeine, instead of relying on garbage collection pressure. A soft cache also hides the cost of your data from monitoring: the heap looks full, and garbage collections get longer as it fills.

ReferenceQueue: being told when an object dies

Checking get() == null tells you that an object died, but you have to poll. A ReferenceQueue turns that into a notification: pass a queue to the reference's constructor, and when the collector clears the reference it enqueues it. You then take references from the queue (poll() returns immediately, remove(timeout) waits) and clean up your own bookkeeping.

The referent is already gone when you get the reference, so a useful trick is to subclass the reference and store whatever you need to remember, such as a key or an id:

Java A registry cleaned through a ReferenceQueue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Three of the four registered objects had no other path, so their TrackedRef objects appeared on the queue; the registry removed their entries, and only the entry for the still-reachable keeper remains. This is the pattern behind many caches and registries: the map holds weak references so that entries do not keep their values alive, and a queue lets the map drop the dead entries (the small reference objects themselves are ordinary objects that would otherwise pile up).

WeakHashMap

You rarely need to write that machinery yourself for maps: java.util.WeakHashMap<K,V> is a Map whose keys are held weakly. When a key is no longer strongly reachable from anywhere else, its entry disappears on its own. It is useful for attaching extra data to objects you do not own ("metadata keyed by object") without extending their lifetime:

Java Entries vanish with their keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The entry for the first key vanished once keyA = null removed the last strong reference, while the entry for keyB stayed. There are three gotchas to remember:

  • Values are held strongly. If a value refers back to its own key, directly or through other objects, the key can never be collected and the entry stays forever. Keep values free of references to their keys.
  • Keys that are never collected are never removed, such as string literals (the JVM keeps them in the string pool), small cached Integer values, enum constants and other long-lived objects. A WeakHashMap<String, X> is therefore a poor choice, since you rarely control the identity of the key strings.
  • Equality still uses equals. A copy of a key that is equal but a different object will find the entry, but it does not keep it alive; only the original key object does.

WeakHashMap is not thread-safe either; wrap it with Collections.synchronizedMap if several threads use it.

PhantomReference and Cleaner

A phantom reference is the weakest kind. get() always returns null, so you can never revive the object through it. It is enqueued only after the object has been finalized and found unreachable, and it exists for one purpose: to run a cleanup action after the object is gone, with no chance of resurrecting it.

You almost never use PhantomReference directly, because Java 9 added java.lang.ref.Cleaner, which wraps it with a background thread. You register an object together with a cleaning action. The action runs when the object becomes unreachable, or earlier if you call clean() on the returned Cleanable (it runs at most once). It replaces finalize(), which is deprecated for removal because it is slow, unpredictable and can resurrect objects.

The design rule: the cleaning action must not hold a reference to the registered object, or the object could never become unreachable. Use a static nested class or a record that holds only the resources to release:

Java Cleaner as a safety net and a phantom reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first handle was closed explicitly in a try-with-resources block, so the action ran immediately, once. The second was never closed. After the collector found it, the cleaner thread ran its action, which prevented a resource leak. That is the right way to think about Cleaner: a safety net behind a real close() method, not a replacement for it. A program that relies on GC timing to free file handles or native memory is fragile, because collection may happen late, or never if the heap stays empty.

The last lines show a bare PhantomReference: get() returns null, and after the collection the reference appears on its queue.

Choosing a reference type

  • Need a cache? Prefer a bounded cache with explicit eviction. Use soft references only for large, easily rebuilt values when you accept unpredictable behavior.
  • Need metadata keyed by objects you do not own? Use WeakHashMap (and keep values from pointing back to their keys), or a map of WeakReferences with a queue.
  • Need to release a native or external resource? Provide close() and implement AutoCloseable, then register a Cleaner action as a backstop.
  • Listeners and callbacks held by a long-lived event source can leak the listeners' owners. Prefer explicit removeListener calls; weak listeners are a last resort, because they can disappear while still wanted.
  • Never use these types to implement program logic that depends on exactly when the collector runs. Behavior differs between collectors, JVM versions and heap sizes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An object is reachable only through a WeakReference. What happens at the next garbage collection?

    Weak references do not keep their referents alive. Once no strong or soft path remains, the collector clears the reference, and get() returns null.
  2. 2. Which reference type does the JVM clear only when it needs memory, before throwing OutOfMemoryError?

    Soft references are kept while memory is plentiful and cleared under pressure, which makes them suited to memory-sensitive caches.
  3. 3. Why should you write Blob b = ref.get(); if (b != null) {...} instead of calling ref.get() twice?

    Copying the result into a local variable creates a strong reference, so the object cannot disappear while you use it.
  4. 4. What is the main rule when writing a Cleaner cleaning action?

    The cleaner itself holds the action strongly. If the action referred to the registered object, the object would always be reachable and never cleaned.
  5. 5. Which statement about WeakHashMap is true?

    Only keys are weak. A value that strongly refers to its key keeps the key reachable, and literals live in the string pool, so their entries stay.

Summary

  • References have four strengths: strong (default), soft (cleared under memory pressure), weak (cleared at the next GC once nothing stronger remains) and phantom (get() is always null, used for cleanup).
  • Always copy ref.get() to a local variable before testing and using it.
  • A ReferenceQueue tells you when references have been cleared, so registries can drop dead entries; subclass the reference to remember an id.
  • WeakHashMap holds keys weakly; values that point back to their keys, and never-collected keys such as string literals, defeat it.
  • Cleaner replaces finalize(): register an action that does not reference the object, and treat it as a safety net behind close().
  • Prefer bounded caches and explicit resource management; use special references only where their trade-offs fit.

Next: JVM Architecture, where you will see how the class loader, runtime data areas and execution engine fit together.