Reference types

A normal variable is a strong reference: as long as it exists, its object stays in memory. The java.lang.ref package adds three weaker kinds that let the garbage collector reclaim an object while you still hold a link to it. This page explains the reachability levels, shows how each kind behaves when the collector runs, measures when soft references are cleared, builds a cache that cleans itself through a reference queue, and runs the traps.

Contents

Reachability and the four strengths

The garbage collector keeps every object that can be reached from a root: local variables of running methods, static fields, and a few JVM internals. An ordinary reference is strong; an object reachable through a chain of strong references is never collected. The java.lang.ref package (Java 1.2) adds reference objects whose link to their referent the collector may cut. From strongest to weakest, an object is:

  1. Strongly reachable: reachable without going through any reference object. Such an object is never collected.
  2. Softly reachable: reachable only through a SoftReference. Kept as long as memory allows; all such objects are guaranteed to be cleared before the JVM throws OutOfMemoryError.
  3. Weakly reachable: reachable only through a WeakReference. Cleared at the next collection that finds it.
  4. Phantom reachable: already finalized or unreachable, but a PhantomReference still tracks it. get() always returns null; the reference exists only to learn that the object is gone.

When a reference is cleared, it can be added to a ReferenceQueue that was passed to its constructor, so a program can find out which objects went away and clean up after them. The reference object itself is an ordinary object and must stay strongly reachable for that to happen.

The reference types
TypeSinceClearedget()Best for
SoftReferenceJava 1.2When memory runs low, oldest-used firstReferent until clearedMemory-sensitive caches, with care
WeakReferenceJava 1.2At the next collectionReferent until clearedMetadata attached to objects you do not own; canonical maps
PhantomReferenceJava 1.2After the object is unreachableAlways nullCleanup after an object is gone; the basis of Cleaner
WeakHashMapJava 1.2Entries go when their key is weakly reachableNot applicablePer-object data keyed by objects you do not own
Reference.refersToJava 16Not applicableTests the referent without a strong copyChecks that must not keep the object alive

Two details changed over time. Since Java 9, a phantom reference is cleared automatically when it is enqueued, like the other kinds; before that, the referent's memory stayed allocated until the program cleared the reference itself. And every reference object costs the collector work: it must discover, process and possibly enqueue each one during a collection, so an application holding millions of weak or soft references spends noticeably longer in garbage collection. Use them for a few thousand cached or attached objects, not as a general-purpose memory management tool.

The programs ran on JDK 21 with the default G1 collector unless noted. They call System.gc() repeatedly to make collections happen on cue; that is a request, which is why real code must never depend on it.

The four strengths under a collection

One object of each strength is created, with the weak and phantom references registered on a queue, and then garbage collection runs.

Java
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FourStrengths {

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

    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<Object> queue = new ReferenceQueue<>();

        Object strongObj = new Object();
        WeakReference<Object> weak = new WeakReference<>(new Object(), queue);
        SoftReference<byte[]> soft = new SoftReference<>(new byte[1024]);
        PhantomReference<Object> phantom = new PhantomReference<>(new Object(), queue);

        System.out.println("before GC: weak alive=" + (weak.get() != null)
                + ", soft alive=" + (soft.get() != null) + ", phantom.get()=" + phantom.get());
        gc();
        System.out.println("after GC:  weak alive=" + (weak.get() != null)
                + ", soft alive=" + (soft.get() != null));

        List<String> enqueued = new ArrayList<>();
        Reference<?> r;
        while ((r = queue.poll()) != null) {
            enqueued.add(r.getClass().getSimpleName());
        }
        Collections.sort(enqueued);                      // the queue order is not specified
        System.out.println("enqueued: " + enqueued);
        System.out.println("strong reference still usable: " + (strongObj != null));
    }
}

Output:

Output
before GC: weak alive=true, soft alive=true, phantom.get()=null
after GC:  weak alive=false, soft alive=true
enqueued: [PhantomReference, WeakReference]
strong reference still usable: true
  • Before the collection, the weak and soft referents were alive, and phantom.get() returned null, as it always does.
  • After the collection, the weak referent was gone and the soft referent was still there: there was plenty of free memory, so the collector had no reason to clear it.
  • Both the weak and the phantom reference were placed on the queue, telling the program that their objects were collected. The order in which references arrive is not specified, so the program sorts the names.
  • The strongly referenced object was never at risk. Most code needs nothing else; the weaker kinds are for the special cases below.

Soft references under memory pressure

Twenty 1 MB arrays are cached through soft references in a JVM limited to 64 MB of heap. After a normal collection the program fills the heap until it runs out, to show the guarantee that soft references are cleared before OutOfMemoryError.

Java
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SoftCache {

    static final Map<Integer, SoftReference<byte[]>> CACHE = new HashMap<>();

    static int cachedEntries() {
        int alive = 0;
        for (SoftReference<byte[]> ref : CACHE.values()) {
            if (ref.get() != null) {
                alive++;
            }
        }
        return alive;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            CACHE.put(i, new SoftReference<>(new byte[1024 * 1024]));     // 20 x 1 MB
        }
        System.gc();
        System.out.println("after a normal GC, entries still cached: " + cachedEntries());

        // Create memory pressure: soft references must be cleared before OutOfMemoryError
        List<byte[]> pressure = new ArrayList<>();
        try {
            while (true) {
                pressure.add(new byte[1024 * 1024]);
            }
        } catch (OutOfMemoryError e) {
            int held = pressure.size();
            pressure.clear();
            System.out.println("under memory pressure, entries still cached: " + cachedEntries());
            System.out.println("the loop held more than 40 MB before running out: " + (held > 40));
        }
    }
}

Output (run with -Xmx64m -XX:+UseSerialGC):

Output
after a normal GC, entries still cached: 20
under memory pressure, entries still cached: 0
the loop held more than 40 MB before running out: true
  • A normal collection kept all 20 entries. Under pressure, all 20 were cleared before the error, which let the allocation loop get further than 40 MB of a 64 MB heap.
  • That is also the problem with soft caches: they are cleared all at once, exactly when the application is short of memory, and until then they make the heap look full, which pushes the collector into more frequent and longer collections. A bounded cache with an explicit size limit and eviction policy is usually more predictable.

When the collector is not desperate, HotSpot decides which soft references to clear with a time-based rule: a softly reachable object survives for -XX:SoftRefLRUPolicyMSPerMB milliseconds (default 1,000) per megabyte of free heap since it was last accessed through get(). The same test runs once with the default and once with the policy set to 0. It checks with refersTo(null), because calling get() would count as an access and reset the clock.

Java
import java.lang.ref.SoftReference;

public class SoftPolicy {

    public static void main(String[] args) throws InterruptedException {
        SoftReference<byte[]> soft = new SoftReference<>(new byte[1 << 20]);
        for (int gc = 1; gc <= 3; gc++) {
            Thread.sleep(100);
            System.gc();
            System.out.println("policy " + System.getProperty("policy") + " ms/MB, after GC " + gc
                    + ": soft reference alive = " + !soft.refersTo(null));
        }
    }
}

Output with the default policy:

Output
policy 1000 ms/MB, after GC 1: soft reference alive = true
policy 1000 ms/MB, after GC 2: soft reference alive = true
policy 1000 ms/MB, after GC 3: soft reference alive = true

Output with -XX:SoftRefLRUPolicyMSPerMB=0:

Output
policy 0 ms/MB, after GC 1: soft reference alive = true
policy 0 ms/MB, after GC 2: soft reference alive = false
policy 0 ms/MB, after GC 3: soft reference alive = false

With the default, the reference survived three full collections, because with hundreds of megabytes free it is allowed to live for minutes. With the policy at 0 it was cleared at the second collection: the collector's clock is updated at each collection, so after one more collection the reference was older than the allowed 0 ms. Setting the flag to 0 makes soft references behave almost like weak ones, which some services do on purpose to stop soft caches from filling the heap.

A cache that cleans itself through a reference queue

Weak references to values need cleanup too: once a value is collected, its map entry is a dead object holding a null reference. A reference queue tells the map which entries to remove. Ten values of 100 KB are cached, and the application still holds 3 of them strongly.

Java
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class WeakValueCache {

    // Each entry remembers its key, so the queue tells us which map entry to remove
    static final class Entry extends WeakReference<byte[]> {
        final int key;

        Entry(int key, byte[] value, ReferenceQueue<byte[]> queue) {
            super(value, queue);
            this.key = key;
        }
    }

    final Map<Integer, Entry> map = new HashMap<>();
    final ReferenceQueue<byte[]> queue = new ReferenceQueue<>();

    void put(int key, byte[] value) {
        expunge();
        map.put(key, new Entry(key, value, queue));
    }

    byte[] get(int key) {
        expunge();
        Entry e = map.get(key);
        return e == null ? null : e.get();        // may be null if just collected
    }

    // Removes entries whose values the GC has cleared
    int expunge() {
        int removed = 0;
        Reference<? extends byte[]> r;
        while ((r = queue.poll()) != null) {
            Entry e = (Entry) r;
            if (map.get(e.key) == e) {             // only if not replaced since
                map.remove(e.key);
                removed++;
            }
        }
        return removed;
    }

    public static void main(String[] args) throws InterruptedException {
        WeakValueCache cache = new WeakValueCache();
        byte[][] inUse = new byte[3][];           // the application still uses 3 values
        for (int i = 0; i < 10; i++) {
            byte[] value = new byte[100000];
            cache.put(i, value);
            if (i < 3) {
                inUse[i] = value;
            }
        }
        System.out.println("entries before GC: " + cache.map.size());
        for (int i = 0; i < 5; i++) {
            System.gc();
            Thread.sleep(50);
        }
        int removed = cache.expunge();
        System.out.println("expunged after GC: " + removed + ", entries left: " + cache.map.size()
                + " " + cache.map.keySet());
        System.out.println("get(0) still works: " + (cache.get(0) == inUse[0]));
        System.out.println("get(7) after collection: " + cache.get(7));
    }
}

Output:

Output
entries before GC: 10
expunged after GC: 7, entries left: 3 [0, 1, 2]
get(0) still works: true
get(7) after collection: null
  • After the collection, the 7 values nobody else referenced were cleared, their Entry references were queued, and expunge() removed exactly those keys. The 3 values the application still held, keys 0 to 2, stayed cached.
  • Subclassing WeakReference to carry the key is the standard technique: the queue hands back the reference object, and the key in it says which entry to remove. WeakHashMap does the same internally, but for weak keys.
  • The check map.get(e.key) == e prevents removing a newer entry that was put under the same key after the old value died.
  • get(7) returned null: callers of a weak or soft cache must always handle a miss and recompute the value.

Reference traps

Reference objects follow simple rules, but the consequences are easy to overlook. Each trap below runs a collection and prints what survived.

Java
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;

public class ReferenceTraps {

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

    record Listener(String name) { }

    public static void main(String[] args) throws InterruptedException {
        // 1. A Reference object that is itself garbage is never enqueued
        ReferenceQueue<Object> queue = new ReferenceQueue<>();
        new PhantomReference<>(new Object(), queue);            // reference not kept
        PhantomReference<Object> kept = new PhantomReference<>(new Object(), queue);
        gc();
        int count = 0;
        while (queue.poll() != null) {
            count++;
        }
        System.out.println("1. two phantom references created, enqueued: " + count
                + " (only the one we kept: " + (kept != null) + ")");

        // 2. Check-then-use: the referent can vanish between two get() calls
        WeakReference<StringBuilder> ref = new WeakReference<>(new StringBuilder("data"));
        StringBuilder local = ref.get();                        // take one strong copy
        gc();
        System.out.println("2. local copy keeps it alive: " + (ref.get() != null)
                + ", value " + local);
        local = null;
        gc();
        System.out.println("2. after the local is dropped: ref.get() = " + ref.get());

        // 3. WeakHashMap: a value that refers to its own key keeps the entry forever
        Map<Object, Object> registry = new WeakHashMap<>();
        Object owner1 = new Object();
        Object owner2 = new Object();
        registry.put(owner1, new Listener("plain"));
        registry.put(owner2, new Object[] {owner2});           // value points back at key
        owner1 = null;
        owner2 = null;
        gc();
        System.out.println("3. WeakHashMap entries after both keys were dropped: "
                + registry.size() + " (the self-referencing one stays)");
    }
}

Output:

Output
1. two phantom references created, enqueued: 1 (only the one we kept: true)
2. local copy keeps it alive: true, value data
2. after the local is dropped: ref.get() = null
3. WeakHashMap entries after both keys were dropped: 1 (the self-referencing one stays)
  1. Two phantom references were created, but only one was enqueued: the program did not keep the first reference object, so it became garbage itself and was never processed. Code that registers references must hold on to them, usually in a set, until they come off the queue; Cleaner does this for you.
  2. Calling ref.get() twice, once to test and once to use, can see the object in the first call and null in the second. Take one strong local copy and use only that; while the local exists, the referent cannot be collected. Once the local was dropped, the referent was gone.
  3. A WeakHashMap holds its values strongly. The entry whose value pointed back at its own key kept that key strongly reachable, so it was never removed, while the plain entry disappeared. Listener registries keyed by owner objects leak this way. Store a WeakReference in the value, or make sure values do not refer to their keys; see WeakHashMap.

One more trap needs no program of its own: a weak reference to an object that something else keeps alive is never cleared. A separate test, with five collections, left new WeakReference<>("literal") and new WeakReference<>(Integer.valueOf(100)) intact, because string literals are held by the class's constant pool and small Integers by the Integer cache, while references to new String("fresh") and Integer.valueOf(100000) were cleared. Tests of weak caches that use literals or small numbers as values therefore pass for the wrong reason.

Choosing a reference type

Which reference to use
NeedUse
A normal object you useA strong reference
A cache with predictable memory useA bounded cache with explicit eviction, not soft references
A cache that may shrink under memory pressureSoftReference values, with misses handled
Extra data attached to objects you do not controlWeakHashMap, with values that do not refer to their keys
A map whose values may be collectedWeakReference values plus a ReferenceQueue to expunge
Releasing native resources after an object is goneCleaner, which wraps phantom references
Test whether a referent is alive without reviving itrefersTo(null)

For how and when collections run, see garbage collection and JVM memory; for finding objects that stay reachable by mistake, see memory leaks.