Java : WeakReference with Examples
WeakReference (Java SE 18 & JDK 18) API Examples.
You will find code examples on most WeakReference methods.
Summary
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)
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)
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.