Java : SoftReference with Examples

SoftReference (Java SE 18 & JDK 18) API Examples.
You will find code examples on most SoftReference methods.


Summary

Soft reference objects, which are cleared at the discretion of the garbage collector in response to memory demand. Soft references are most often used to implement memory-sensitive caches.

Class diagram

var sb = new StringBuilder("abcd");
final var ref = new SoftReference<>(sb);

System.gc();
System.out.println(ref.get()); // abcd

sb = null;

System.gc();
System.out.println(ref.get()); // abcd

try {
    // Intentionally throw an OutOfMemoryError.
    final var bytes = new byte[1000000000];
} catch (OutOfMemoryError e) {
    System.out.println(e.getMessage()); // Java heap space
}

// All soft references to softly-reachable objects are guaranteed to have been 
// cleared before the virtual machine throws an OutOfMemoryError.
System.out.println(ref.get()); // null

Constructors

SoftReference (T referent)

Creates a new soft reference that refers to the given object.

var sb = new StringBuilder("abcd");
final var ref = new SoftReference<>(sb);

System.out.println(ref.get()); // abcd

sb = null;
System.gc();
System.out.println(ref.get()); // abcd

try {
    final var bytes = new byte[1000000000];
} catch (OutOfMemoryError e) {
    System.out.println(e.getMessage()); // Java heap space
}

System.out.println(ref.get()); // null

SoftReference (T referent, ReferenceQueue<? super T> q)

Creates a new soft reference that refers to the given object and is registered with the given queue.

final var queue = new ReferenceQueue<StringBuilder>();

var sb = new StringBuilder("abcd");
final var ref = new SoftReference<>(sb, queue);

System.out.println(ref.get()); // abcd
System.out.println(queue.poll()); // null

sb = null;
System.gc();
System.out.println(ref.get()); // abcd
System.out.println(queue.poll()); // null

try {
    final var bytes = new byte[1000000000];
} catch (OutOfMemoryError e) {
    System.out.println(e.getMessage()); // Java heap space
}

System.out.println(ref.get()); // null
System.out.println(queue.poll()); // java.lang.ref.SoftReference@63bfd328

Methods

T get ()

Returns this reference object's referent.

Please see SoftReference(T referent).

Methods declared in Reference

clear, clone, enqueue, isEnqueued, reachabilityFence, refersTo

Please see the link below.


Related posts

To top of page