Java : SoftReference with Examples
SoftReference (Java SE 18 & JDK 18) API Examples.
You will find code examples on most SoftReference methods.
Summary
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)
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)
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 ()
Please see SoftReference(T referent).
Methods declared in Reference
clear, clone, enqueue, isEnqueued, reachabilityFence, refersTo
Please see the link below.