Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Inside the JVM

    Reference Types: Strong, Soft, Weak, Phantom

    Object big — new byte[10000000];

    Chapter 9 of 103 min read

    The Plain Picture#

    • A rope tying you to an object: as long as you hold it, the object stays. (Strong)

    • A rubber band: it holds, but if the room is running out of space, the cleaners may cut it. (Soft)

    • A thread: the cleaners cut it at the very next clean-up if nothing stronger is attached. (Weak)

    • A note saying "tell me when it's gone": you can't use the object through it at all. (Phantom)

    The Real Names#

    TypeCollected whenUse
    strong (a normal reference)never, while reachableeverything by default
    SoftReferenceonly when memory is running lowmemory-sensitive caches
    WeakReferenceat the next GC, if only weakly reachablecaches keyed by objects (WeakHashMap — Collections, From the Inside Ch 10), listener registries
    PhantomReferenceafter it's been collected — used with a queue for clean-up notificationreleasing native resources (java.lang.ref.Cleaner builds on it)

    Measured:

    Java
    Object big = new byte[10_000_000];
    
    WeakReference<Object> weak = new WeakReference<>(big);
    
    System.out.println("before: " + (weak.get() != null)); // before: true
    
    big = null; // remove the only strong reference
    
    System.gc(); // a HINT to run a GC (not guaranteed)
    
    System.out.println("after GC: " + (weak.get() != null)); // after GC: false

    finalize() — the old way to run clean-up when an object is collected — is deprecated: it's slow, unpredictable, and can resurrect objects. Use try-with-resources for resources (Exceptions and Generics Ch 4), and Cleaner as a last-resort safety net.

    Check yourself

    3 questions
    1

    What happens to an object reachable only through a WeakReference?

    Show answer

    It's collected at the next GC, and get() then returns null.

    2

    Why is SoftReference suited to caches?

    Show answer

    Its referent survives until memory runs low, so cached data is kept while there's room and dropped under pressure.

    3

    What replaced finalize()?

    Show answer

    try-with-resources for deterministic clean-up, with java.lang.ref.Cleaner as a safety net.