Skip to content

Commit 15a0f7a

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

0 commit comments

Comments
 (0)