Skip to content

Commit 7e724b0

Browse files
committed
SoftReference vs WeakReference vs PhantomReference.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 90ace8b commit 7e724b0

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
SoftReference vs WeakReference vs PhantomReference:
2+
3+
1. Background:
4+
- In Java, garbage collection (GC) automatically reclaims memory of objects that are no longer reachable.
5+
- Normally, objects are referenced via **strong references**, meaning they will never be collected as long as a
6+
strong reference exists.
7+
- To give more flexibility in memory-sensitive or resource-sensitive applications, Java provides special reference
8+
types:
9+
• SoftReference
10+
• WeakReference
11+
• PhantomReference
12+
13+
These references help developers influence GC behavior in specific scenarios such as caching, memory management, or
14+
native resource cleanup.
15+
16+
2. SoftReference
17+
- Definition:
18+
A SoftReference keeps an object reachable *until memory pressure occurs*.
19+
The GC will clear softly reachable objects **only when JVM needs memory**.
20+
21+
- Why use:
22+
Useful for implementing memory-sensitive caches (e.g., image cache, large data cache).
23+
The cached objects stay in memory as long as possible but are discarded automatically when JVM runs low on memory.
24+
25+
- Application examples:
26+
• Web browsers caching images or pages.
27+
• Large in-memory caches that should shrink automatically under memory pressure.
28+
• Situations where data can be recomputed or re-fetched if evicted.
29+
30+
----------------------------------------
31+
3. WeakReference
32+
----------------------------------------
33+
- Definition:
34+
A WeakReference does not prevent its referent from being collected.
35+
Once no strong (or soft) references exist, the object becomes weakly reachable and GC will reclaim it eagerly.
36+
37+
- Why use:
38+
Ideal when you want to associate metadata with an object **without preventing it from being collected**.
39+
For example, a map where keys should disappear once the actual object is gone.
40+
41+
- Application examples:
42+
• WeakHashMap (commonly used for caches of metadata).
43+
• Listener or callback registries, where you don’t want listeners to keep objects alive.
44+
• Interning or canonicalizing maps where duplicate objects should be merged but freed if unused.
45+
46+
4. PhantomReference
47+
- Definition:
48+
PhantomReferences are enqueued **after the object has been finalized** but before its memory is reclaimed.
49+
They always return null from `get()`, and must be used with a ReferenceQueue.
50+
51+
- Why use:
52+
They give you a reliable hook to perform cleanup actions after the object is no longer reachable.
53+
This is safer and more flexible than finalizers (which are deprecated).
54+
55+
- Application examples:
56+
• Releasing native resources (file handles, sockets, direct memory).
57+
• Implementing custom memory managers or resource pools.
58+
• Framework-level cleanup tasks (like advanced caching libraries).
59+
60+
5. ASCII Summary of Reachability
61+
Strong Ref → Object (alive, never GC)
62+
Soft Ref → Object (collected under memory pressure)
63+
Weak Ref → Object (collected eagerly when no strong refs)
64+
Phantom Ref→ (no access; only cleanup notification before GC frees memory)
65+
66+
6. When to Use What?
67+
- SoftReference:
68+
Use for caches that can be recomputed/reloaded. Survive GC until memory is tight.
69+
- WeakReference:
70+
Use for mappings/registries where you do not want the reference to keep objects alive.
71+
- PhantomReference:
72+
Use for advanced cleanup of external resources (native memory, sockets, files). Provides exact point of reclamation.
73+
74+
7. Real-world Usage Scenarios
75+
✔ Android image loading libraries (Glide, Picasso) use SoftReference/WeakReference for memory-sensitive caches.
76+
✔ WeakHashMap internally uses WeakReference for keys, letting them vanish once not strongly referenced.
77+
✔ JVM internals and frameworks sometimes use PhantomReference for resource cleanup instead of finalizers.
78+
✔ Database connection pools or large native buffers can be tracked via PhantomReference to ensure they are released properly.
79+
80+
8. Key Takeaway
81+
These references exist to provide finer control over how objects are treated by GC:
82+
- Soft → "Keep as long as possible but discard under pressure."
83+
- Weak → "Don’t keep alive; free as soon as no one else needs it."
84+
- Phantom → "I don’t need the object, just notify me when it’s gone so I can clean resources."
85+
86+
They help balance performance, memory efficiency, and safe cleanup in complex applications.

0 commit comments

Comments
 (0)