Skip to content

Commit a2b9af8

Browse files
committed
feat(PhantomDemo): add demo of PhantomReference with ReferenceQueue cleanup
What - Implemented `PhantomDemo` to illustrate PhantomReference usage. - Created `NativeResource` object with strong ref, then wrapped in PhantomReference. - Demonstrated that `pr.get()` always returns null. - Released strong reference and triggered GC. - Checked ReferenceQueue to detect when PhantomReference was enqueued. Why - To show how PhantomReferences differ from soft/weak references. - Useful for safe cleanup of native resources (files, sockets, off-heap memory). - Demonstrates advanced reference handling beyond GC reachability. How - Step 1: Create `NativeResource res = new NativeResource(1)`. - Step 2: Wrap in `PhantomReference<>(res, queue)`. - Step 3: Print `pr.get()` (always null). - Step 4: Nullify strong reference and call `System.gc()`. - Step 5: Sleep briefly to allow GC. - Step 6: Poll ReferenceQueue, if enqueued → cleanup and call `clear()`. Logic - Inputs: - `NativeResource` created with id. - Outputs: - Console log: `pr.get() = null`. - Console log: `"Phantom enqueued — cleanup now"` when GC clears resource. - Flow: 1. Strong + phantom references exist. 2. Strong reference nulled → object becomes phantom-reachable. 3. GC enqueues PhantomReference in ReferenceQueue. 4. Application detects it and performs cleanup. - Constraints: - GC timing is not deterministic; ReferenceQueue polling may return null if GC not run. - Complexity: - O(1) for enqueue/dequeue operations. Real-life applications - PhantomReference used for post-mortem cleanup tasks. - Manage large native resources (direct buffers, file handles). - Used by JVM itself in DirectByteBuffer deallocation. Notes - `pr.get()` always returns null (unlike soft/weak references). - Must use ReferenceQueue to detect GC of phantom-referenced objects. - Part of Java’s 3-tier reference system: ✔ SoftReference → caches ✔ WeakReference → weak keys, listeners ✔ PhantomReference → cleanup hooks after finalization Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 7741613 commit a2b9af8

File tree

1 file changed

+35
-0
lines changed
  • Section 25 Collections Frameworks/Map Interface/Garbage Collection/SoftReference vs WeakReference vs PhantomReference/src

1 file changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.lang.ref.PhantomReference;
2+
import java.lang.ref.Reference;
3+
import java.lang.ref.ReferenceQueue;
4+
5+
public class PhantomDemo {
6+
static class NativeResource {
7+
private final int id;
8+
NativeResource(int id) { this.id = id; }
9+
@Override public String toString() { return "NR#" + id; }
10+
}
11+
public static void main(String[] args) throws InterruptedException {
12+
ReferenceQueue<NativeResource> queue = new ReferenceQueue<>();
13+
NativeResource res = new NativeResource(1);
14+
15+
PhantomReference<NativeResource> pr = new PhantomReference<>(res, queue);
16+
17+
System.out.println("pr.get() = " + pr.get()); // always null
18+
res = null; // drop strong reference
19+
20+
System.gc();
21+
Thread.sleep(200);
22+
23+
Reference<? extends NativeResource> r = queue.poll();
24+
if (r != null) {
25+
System.out.println("Phantom enqueued — cleanup now");
26+
r.clear();
27+
}
28+
}
29+
}
30+
31+
/*
32+
• SoftReference → Cache data that can be reloaded (but let JVM evict under memory pressure).
33+
• WeakReference → Avoid preventing GC (e.g., weak keys in maps, listener cleanup).
34+
• PhantomReference → Do resource cleanup safely (close files, free native memory).
35+
*/

0 commit comments

Comments
 (0)