Commit 7741613
committed
feat(WeakReferenceDemo): add demo of WeakReference behavior and GC collection
What
- Added `WeakReferenceDemo` class.
- Created `Phone` object with a strong reference.
- Wrapped object in a `WeakReference<Phone>`.
- Printed object before and after nullifying strong reference and invoking GC.
Why
- To demonstrate how weak references behave in Java.
- Show that weak references do not prevent GC from reclaiming an object.
- Illustrate memory-sensitive referencing useful for caches and temporary objects.
How
- Step 1: Create strong reference `phone` → new Phone("Apple", "16 Pro").
- Step 2: Wrap in WeakReference (`phoneWeakReference`).
- Step 3: Print value via weak reference before GC.
- Step 4: Nullify strong reference (`phone = null`).
- Step 5: Call `System.gc()` and wait briefly.
- Step 6: Print value via weak reference again (likely null).
Logic
- Inputs:
- Phone constructor with brand and model.
- Outputs:
- Console log showing object before GC.
- Console log showing null after GC (if collected).
- Flow:
1. Strong + weak references exist.
2. Strong reference nulled → only weak reference remains.
3. GC may reclaim object and clear weak reference.
4. `get()` returns null when object collected.
- Constraints:
- GC timing is not deterministic; output may vary.
- Complexity:
- O(1) for WeakReference operations.
Real-life applications
- Weak references prevent memory leaks in caches, maps, and listeners.
- Commonly used in `WeakHashMap`.
- Useful when objects should be reclaimed automatically under memory pressure.
Notes
- Strong references prevent GC, weak references do not.
- WeakReference `.get()` may return null anytime after GC.
- Demonstrates difference between strong and weak references clearly.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 28d7664 commit 7741613
File tree
1 file changed
+34
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Garbage Collection/src
1 file changed
+34
-0
lines changedLines changed: 34 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 | + | |
0 commit comments