Java core learning path Level 3 This level · 7 of 19
Medium java java-21

What are strong, soft, weak and phantom references, and when can the GC collect each?

The 30 second answer

A normal reference is strong, and the GC never collects an object that is strongly reachable. A soft reference lets the GC clear the object when memory gets tight, and always before an OutOfMemoryError. A weak reference is cleared at the next GC once nothing strong points to the object. A phantom reference never returns the object; it only tells you after the object is gone, so you can run cleanup, which is what Cleaner does.

Could you say this in an interview?

The four levels of reachability. The java.lang.ref package defines them, each weaker than the last. An object is strongly reachable if some thread can reach it without going through any reference object; that is every ordinary variable, field and collection entry, and the GC never collects it. It is softly reachable if the only path to it goes through a SoftReference, weakly reachable if the only path goes through a WeakReference, and phantom reachable if only a PhantomReference points to it. When none of these applies, the object is unreachable and its memory can be reclaimed. The GC decides by walking from the GC roots (thread stacks, static fields and JVM internals), so what counts is the strongest path to the object, not how many references there are.

When the GC can collect the referent.

Typeget() returnsWhen the GC can clear itTypical use
Strong (a normal reference)The objectNever, while the reference is reachableEverything you write normally
SoftReferenceThe object, until clearedWhen memory is needed; guaranteed before an OutOfMemoryErrorMemory-sensitive caches
WeakReferenceThe object, until clearedAt the next GC once no strong or soft path remainsMaps that must not keep their keys alive: WeakHashMap, ThreadLocalMap keys, listener registries
PhantomReferenceAlways nullEnqueued only after the object is no longer reachable in any other wayPost-mortem cleanup of native or off-heap resources, via Cleaner

Soft references. The Javadoc guarantees that all soft references to softly reachable objects are cleared before the JVM throws an OutOfMemoryError, and encourages JVMs to keep recently created or recently used ones longer. HotSpot controls this with -XX:SoftRefLRUPolicyMSPerMB, which defaults to 1000: after the last strong reference is gone, a soft reference survives roughly one second for each free megabyte of heap. So the eviction is decided by the GC and depends on free heap, not on your cache's size or hit rate. That is why the Caffeine cache documentation recommends a maximum cache size instead of softValues() in most cases. [Opinion] In a server I treat soft references as a last-resort safety net, not as a cache policy: a heap full of soft references looks full in monitoring, gets cleared all at once under pressure, and then the cache refills with a burst of expensive work.

Weak references. A weakly reachable object is cleared at the next collection, so a weak reference never keeps anything alive. This fits mappings where the entry should disappear when the key's owner is gone. WeakHashMap holds its keys weakly and removes stale entries the next time the map is used, because it polls a reference queue on access. The trap is in its Javadoc: the values are held strongly, so if a value refers back to its own key, the key never becomes weakly reachable and the entry never goes away. ThreadLocalMap uses the same pattern, with a weak key and a strong value, which is why a forgotten ThreadLocal value can still leak on a pooled thread. For listener registries, a weak reference to the listener means a component that forgets to unregister doesn't leak, though the explicit unregister is still clearer.

Phantom references. PhantomReference.get() always returns null, so you can never bring the object back to life. You create it with a ReferenceQueue, and the reference shows up in the queue after the object has become unreachable, which is the moment to release something the object owned outside the heap, such as a native handle or a direct buffer. Since Java 9 the standard way to do this is java.lang.ref.Cleaner, which manages phantom references and a cleanup thread for you. The Cleaner Javadoc warns that the cleaning action must not refer to the object being registered; a lambda that touches the object's fields captures it and keeps it reachable forever. Cleaner replaces finalize(), which was deprecated in Java 9 and deprecated for removal in Java 18 (JEP 421). [Opinion] Cleaner is a safety net. Resources that matter should still be closed explicitly with try-with-resources.

How they differ, in one line each. Strong keeps the object alive. Soft keeps it alive until memory is short. Weak does not keep it alive at all, but still lets you read it until the next GC. Phantom never lets you read it and only tells you it is gone.

A runnable demo. One program shows all four, plus WeakHashMap and Cleaner. I ran it on OpenJDK 21 with a small heap, java -Xmx64m ReferenceTypesDemo, so the soft reference clears under pressure:

import java.lang.ref.Cleaner;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.WeakHashMap;

public class ReferenceTypesDemo {

    static final Cleaner CLEANER = Cleaner.create();

    static void gc() throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            System.gc();
            Thread.sleep(50);
        }
    }

    public static void main(String[] args) throws Exception {
        // 1) Strong: as long as the variable points to it, GC never collects it.
        byte[] strong = new byte[1_000_000];

        // 2) Weak: cleared at the next GC once no strong reference is left.
        var weak = new WeakReference<>(new byte[1_000_000]);

        // 3) Soft: kept while there is enough free heap, cleared before an OutOfMemoryError.
        var soft = new SoftReference<>(new byte[1_000_000]);

        // 4) Phantom: get() always returns null; it is only enqueued after the object is gone.
        var queue = new ReferenceQueue<>();
        var phantom = new PhantomReference<>(new byte[1_000_000], queue);

        gc();
        System.out.println("after GC, plenty of heap:");
        System.out.println("  strong  = " + strong.length + " bytes");
        System.out.println("  weak    = " + weak.get());
        System.out.println("  soft    = " + (soft.get() == null ? "null" : "still there"));
        System.out.println("  phantom = get() returns " + phantom.get()
                + ", enqueued = " + (queue.remove(1000) == phantom));

        // Fill the heap: the JVM must clear soft references before throwing OutOfMemoryError.
        var hog = new ArrayList<>();
        try {
            while (true) {
                hog.add(new byte[1_000_000]);
            }
        } catch (OutOfMemoryError e) {
            hog.clear();
        }
        System.out.println("after memory pressure:");
        System.out.println("  soft    = " + soft.get());

        // WeakHashMap: the entry disappears once the key is no longer strongly reachable.
        var listeners = new WeakHashMap<>();
        Object session = new Object();
        listeners.put(session, "on-price-change");
        session = null;
        gc();
        System.out.println("WeakHashMap size after the key is dropped: " + listeners.size());

        // Cleaner (built on phantom references): post-mortem cleanup without finalize().
        Object nativeBuffer = new Object();
        CLEANER.register(nativeBuffer, () -> System.out.println("Cleaner: releasing native buffer"));
        nativeBuffer = null;
        gc();
        Thread.sleep(200);
    }
}

Output on OpenJDK 21, the same on three runs:

after GC, plenty of heap:
  strong  = 1000000 bytes
  weak    = null
  soft    = still there
  phantom = get() returns null, enqueued = true
after memory pressure:
  soft    = null
WeakHashMap size after the key is dropped: 0
Cleaner: releasing native buffer

System.gc() is only a request, so the demo calls it a few times with short pauses. Real code should never depend on it. The OutOfMemoryError loop is there only to show the soft reference guarantee, and catching that error is not something to do in production code.

Does it matter for a search team? Yes, mostly as a memory and GC pressure topic. Search services keep large caches (query results, filters, field data) and off-heap resources such as memory-mapped index files and direct buffers. You should be able to explain why a size-bounded cache beats a soft-reference cache for predictable latency, why a weak-key map can still leak through its values, and how phantom references and Cleaner free native memory only after a GC, so off-heap usage can lag behind heap usage.

Alternate interview scenarios

"Our cache uses SoftReference values, and every few hours p99 latency spikes. Why?"

Under heap pressure the GC clears many soft references at once, then the cache misses and recomputes in a burst. Confirm with GC logs and cache hit rate over time, then switch to a size-bounded cache with a maximum size and expiry.

"We used a WeakHashMap for listeners and it still leaks. What went wrong?"

Check whether each value, often the callback, strongly refers back to its key, for example a lambda that captures the session object. If it does, the key never becomes weakly reachable. Take a heap dump and look at the path from the GC roots to one of the keys.

Sources (9)
  1. java.lang.ref package summary: reachability and reference queues (Java 21)docs.oracle.com
  2. SoftReference Javadoc (Java 21)docs.oracle.com
  3. WeakReference Javadoc (Java 21)docs.oracle.com
  4. PhantomReference Javadoc (Java 21)docs.oracle.com
  5. Cleaner Javadoc (Java 21)docs.oracle.com
  6. WeakHashMap Javadoc (Java 21)docs.oracle.com
  7. HotSpot GC Tuning Guide, Other Considerations: soft references and finalization (Java 21)docs.oracle.com
  8. JEP 421: Deprecate Finalization for Removalopenjdk.org
  9. Caffeine wiki: Eviction (reference-based eviction)github.com
Previous
Next