Java : WeakReference with Examples

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


Summary

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.

Class diagram

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

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

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

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

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

Constructors

WeakReference (T referent)

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

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

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

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

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

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

Creates a new weak 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 WeakReference<>(sb, queue);

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

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

System.gc();
System.out.println(ref.get()); // null
System.out.println(queue.poll()); // java.lang.ref.WeakReference@6b2a628e

Methods declared in Reference

clear, clone, enqueue, get, isEnqueued, reachabilityFence, refersTo

Please see the link below.


Related posts

To top of page