Commit 15a0f7a
committed
feat(WeakRefExample): add WeakReference demo showing GC behavior
What
- Added `WeakRefExample` to demonstrate how `WeakReference` works.
- Created strong reference to an `Object` and a corresponding `WeakReference`.
- Printed `weak.get()` before and after clearing the strong reference and running GC.
Why
- To show that weakly referenced objects are not protected from GC.
- Useful for scenarios like weak maps or listener registries where you don’t want references to prevent cleanup.
How
- Step 1: Create strong reference `Object strong = new Object()`.
- Step 2: Wrap in `WeakReference<Object> weak = new WeakReference<>(strong)`.
- Step 3: Print `weak.get()` → non-null when strong reference exists.
- Step 4: Nullify strong reference and run `System.gc()`.
- Step 5: Print `weak.get()` again → usually null after GC reclaims object.
Logic
- Inputs: none.
- Outputs:
- Before GC: `weak.get()` prints object reference.
- After GC: `weak.get()` returns null (object collected).
- Flow:
1. Both strong + weak refs exist → object alive.
2. Strong ref cleared → only weak ref remains.
3. GC reclaims object promptly → weak.get() → null.
- Determinism: highly likely to be null after GC, though GC timing is not guaranteed.
Real-life applications
- `WeakHashMap` keys: allows keys to be collected when not used elsewhere.
- Event listeners or caches that should not extend object lifetime.
- Avoiding memory leaks when referencing large, disposable objects.
Notes
- Unlike SoftReference, WeakReference objects are collected eagerly on next GC.
- `weak.get()` may return null immediately after GC.
- Always design weak-reference use cases assuming referenced object can vanish at any time.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 51ad4a8 commit 15a0f7a
File tree
1 file changed
+15
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Garbage Collection/SoftReference vs WeakReference vs PhantomReference/src
1 file changed
+15
-0
lines changedLines changed: 15 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 | + | |
0 commit comments