Commit 51ad4a8
committed
feat(SoftRefExample): add SoftReference demo showing GC-sensitive caching
What
- Added `SoftRefExample` to illustrate how `SoftReference` works.
- Created strong reference to `Object` and wrapped it in a `SoftReference`.
- Printed `soft.get()` before and after GC, with strong reference nulled.
Why
- To demonstrate `SoftReference` behavior: objects remain until JVM detects memory pressure.
- Shows how soft refs are often used for caching—retained as long as memory is available, reclaimed when needed.
How
- Step 1: Create `Object strong = new Object()`.
- Step 2: Wrap in `SoftReference<Object> soft = new SoftReference<>(strong)`.
- Step 3: Print `soft.get()` → non-null while strong exists.
- Step 4: Nullify `strong` and call `System.gc()`.
- Step 5: Print `soft.get()` again, may be null if GC needed memory.
Logic
- Inputs: none.
- Outputs:
- Before GC: `soft.get()` prints object reference.
- After GC: may remain non-null (if JVM has enough memory), or null (if reclaimed).
- Flow:
1. Strong + soft reference exist → object alive.
2. Strong ref nulled, GC run.
3. If JVM decides memory is tight → object reclaimed, `soft.get()` returns null.
- Non-determinism: GC may or may not reclaim soft refs depending on memory conditions.
Real-life applications
- Implementing memory-sensitive caches (e.g., image caches).
- Holding data that can be recomputed or reloaded if evicted.
- Avoiding OutOfMemoryErrors by letting JVM discard cache entries automatically.
Notes
- Unlike `WeakReference`, soft refs survive at least one GC if memory is sufficient.
- Good for caches, but not for critical resources.
- JVM-specific behavior: reclamation timing is implementation-dependent.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 45c4a96 commit 51ad4a8
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