This is merely a short snippet to illustration how to use weak ref in Java.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.lang.ref.*;

public class weak {
public static void main(String[] args) throws InterruptedException {
String obj = new String("Random");

ReferenceQueue<String> queue = new ReferenceQueue<>();
WeakReference<String> weak_ref = new WeakReference<>(obj, queue);

System.out.println("weak ref: " + weak_ref);

// drop strong ref to the object
obj = null;

while (!weak_ref.isEnqueued()) {
// loop until weak ref is enqueued
System.gc();
}

System.out.println("weak ref enqueued: " + queue.poll());
System.out.println("referent nullified: " + weak_ref.get());

}
}

Output is the following. So, when the referent becomes collectible, the enclosing weak ref is enqueued into the registered ref queue, which provides a way to inform the application of such reachability change.

1
2
3
weak ref: java.lang.ref.WeakReference@50f8360d
weak ref enqueued: java.lang.ref.WeakReference@50f8360d
referent nullified: null