Java : Reference with Examples
Reference (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Reference methods.
Summary
// An example with WeakReference.
var sb = new StringBuilder("abcd");
final Reference<StringBuilder> 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
Methods
void clear ()
final var sb = new StringBuilder("abcd");
final Reference<StringBuilder> ref = new WeakReference<>(sb);
System.out.println(ref.get()); // abcd
ref.clear();
System.out.println(ref.get()); // null
final var sb = new StringBuilder("abcd");
final var queue = new ReferenceQueue<StringBuilder>();
final Reference<StringBuilder> ref = new WeakReference<>(sb, queue);
System.out.println(ref.get()); // abcd
ref.clear();
System.out.println(ref.get()); // null
// No queue.
System.out.println(queue.poll()); // null
protected Object clone ()
final var sb = new StringBuilder("abcd");
final var ref = new WeakReference<StringBuilder>(sb) {
public void test() {
try {
clone();
} catch (CloneNotSupportedException e) {
System.out.println("CloneNotSupportedException!");
}
}
};
ref.test();
// Result
// ↓
//CloneNotSupportedException!
boolean enqueue ()
final var sb = new StringBuilder("abcd");
final var queue = new ReferenceQueue<StringBuilder>();
final Reference<StringBuilder> ref = new WeakReference<>(sb, queue);
System.out.println(ref.get()); // abcd
final var ret = ref.enqueue();
System.out.println(ret); // true
System.out.println(ref.get()); // null
System.out.println(queue.poll()); // java.lang.ref.WeakReference@7625b376
final var sb = new StringBuilder("abcd");
final Reference<StringBuilder> ref = new WeakReference<>(sb);
System.out.println(ref.get()); // abcd
final var ret = ref.enqueue();
System.out.println(ret); // false
System.out.println(ref.get()); // null
T get ()
var sb = new StringBuilder("abcd");
final Reference<StringBuilder> 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
boolean isEnqueued ()
Deprecated.
static void reachabilityFence (Object ref)
I haven't fully confirmed the behavior yet, so I don't have a code example ready. (I may update it later...)
final boolean refersTo (T obj)
var sb1 = new StringBuilder("abcd");
final Reference<StringBuilder> ref = new WeakReference<>(sb1);
System.out.println(ref.refersTo(sb1)); // true
var sb2 = new StringBuilder("XYZ");
System.out.println(ref.refersTo(sb2)); // false
Related posts
- API Examples