Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

SoftReference — a soft reference

SoftReference<T> in java.lang.ref holds a soft reference to an object. Once the object is no longer strongly reachable, the garbage collector may clear that reference in response to memory demand. Reading it through get() requires handling null.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

new SoftReference<T>(referent)
new SoftReference<T>(referent, queue)
T value = reference.get();
reference.clear();

SoftReference<T> wraps a reference to an object of type T. An object is softly reachable if it is not strongly reachable but can be reached through a soft reference. Strong reachability does not require traversing reference objects; weak reachability excludes both strong and soft reachability.

The garbage collector may clear soft references under memory pressure. Clearing has no guaranteed timing or ordering, although all soft references to softly reachable objects will be cleared before an OutOfMemoryError is thrown. This supports memory-sensitive caches, not guaranteed retention periods or protection against running out of memory.

get() returns a strong reference to the object or null. Store the result once in a local variable and check it before use. clear() clears the reference, but does not delete the object or other references and does not enqueue the wrapper. The constructor SoftReference(T referent, ReferenceQueue<? super T> q) allows queue registration; keep the wrapper itself reachable if you expect notification.

The example explicitly calls clear() rather than making its output depend on garbage collection. Reference.reachabilityFence(value) keeps value strongly reachable until that point. Consequently, the first read is predictable, and the saved snapshot remains available after the wrapper is cleared.

Examples

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;

public class SoftReferenceDemo {
    public static void main(String[] args) {
        String value = new String("cached");
        SoftReference<String> reference = new SoftReference<>(value);

        String snapshot = reference.get();
        System.out.println(snapshot);
        reference.clear();
        System.out.println(reference.get());
        System.out.println(snapshot);
        Reference.reachabilityFence(value);
    }
}

Result

cached
null
cached

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources