Commit a2b9af8
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 changedLines changed: 35 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
0 commit comments