Commit 90ace8b
committed
feat(PhantomDemo1): add PhantomReference + ReferenceQueue cleanup example
What
- Added `PhantomDemo1` to demonstrate PhantomReference lifecycle.
- Created `NativeResource` wrapped in PhantomReference with ReferenceQueue.
- Showed that `pr.get()` always returns null.
- Dropped strong reference, triggered GC, and checked ReferenceQueue.
- Printed cleanup message if PhantomReference enqueued.
Why
- To illustrate safe post-GC cleanup without relying on finalizers.
- PhantomReference is essential for releasing non-Java resources (native memory, file handles).
- Complements SoftReference (caching) and WeakReference (maps/listeners).
How
- Step 1: Define `NativeResource` with `id`.
- Step 2: Instantiate and wrap in `PhantomReference<>(res, queue)`.
- Step 3: Print `pr.get()` → always null.
- Step 4: Nullify `res`, suggest GC via `System.gc()`.
- Step 5: Sleep briefly for GC.
- Step 6: Poll ReferenceQueue; if enqueued, log cleanup and call `clear()`.
Logic
- Inputs: new `NativeResource(1)`.
- Outputs:
- Console log before GC: `before nulling res, pr.get() = null`.
- After GC, either:
- `"Phantom enqueued — do cleanup now for ..."`, or
- `"No phantom enqueued yet."`.
- Flow:
1. Strong + phantom refs exist.
2. Strong ref dropped → object phantom-reachable.
3. GC clears object → PhantomReference enqueued.
4. Application detects and performs cleanup.
- Complexity: O(1) for ReferenceQueue operations.
- Non-determinism: GC may or may not run immediately, so queue.poll() may return null.
Real-life applications
- Safe cleanup of DirectByteBuffers (off-heap memory).
- Closing file handles or sockets after object reclamation.
- Resource tracking in JVM-managed frameworks.
Notes
- PhantomReference is the lowest-level reference type in Java’s hierarchy.
- Unlike soft/weak refs, `get()` always returns null.
- Cleanup must be done through ReferenceQueue.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent a2b9af8 commit 90ace8b
File tree
1 file changed
+40
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Garbage Collection/SoftReference vs WeakReference vs PhantomReference/src
1 file changed
+40
-0
lines changedLines changed: 40 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 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
0 commit comments