Skip to content

Commit 51ad4a8

Browse files
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 changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import java.lang.ref.SoftReference;
2+
3+
public class SoftRefExample {
4+
public static void main(String[] args) {
5+
Object strong = new Object();
6+
SoftReference<Object> soft = new SoftReference<>(strong);
7+
8+
System.out.println("soft.get(): " + soft.get()); // likely non-null
9+
10+
strong = null; // drop strong ref
11+
System.gc();
12+
13+
System.out.println("after GC soft.get(): " + soft.get()); // null if memory low
14+
}
15+
}

0 commit comments

Comments
 (0)