All topics
library
advanced

Weak, Soft & Phantom References

Understand Java reference types for memory-sensitive caching and resource cleanup without finalize().

Java has four reference strengths, controlling when the GC can reclaim objects:

Strong reference = owning a car (can't be towed while you own it). Soft reference = renting a parking spot (car stays until lot is full). Weak reference = parking on the street (towed anytime). Phantom reference = the tow notification (car is gone, you just get told about it).

Key Concepts

1
1. Strong reference (normal): Object obj = new Object(). GC never collects while a strong reference exists.
2
2. SoftReference<T>: GC collects only when memory is low (before OutOfMemoryError). Ideal for memory-sensitive caches. JVM tries to keep them alive as long as possible.
3
3. WeakReference<T>: GC collects at the next GC cycle, regardless of memory pressure. Used in WeakHashMap — entries are removed when the key is no longer strongly referenced elsewhere.
4
4. PhantomReference<T>: get() always returns null. Used with ReferenceQueue to get notified when an object is about to be GC'd. Replacement for finalize() (deprecated in Java 9). Used for cleanup actions (like Cleaner).
5
ReferenceQueue: soft, weak, and phantom references can be registered with a queue. When the referent is collected, the reference object is enqueued. A background thread polls the queue and performs cleanup.
6
WeakHashMap: a Map where keys are weak references. When a key has no strong references, the entry is automatically removed. Used for canonical maps, caches keyed by objects whose lifecycle you don't control.
7
Cleaner (Java 9): replaces finalize(). Register a cleaning action with Cleaner; when the object becomes phantom-reachable, the action runs on a separate thread.