Java Memory Model
Reference Types
Understand Strong, Soft, Weak, and Phantom references and their interaction with the GC.
Interview: Commonly tested on implementing caches (e.g. WeakHashMap) and understanding phantom references with reference queues.
In Java, reference wrappers allow customizing how long objects remain in memory relative to JVM garbage collector pressure.
Core Idea
Soft, Weak, and Phantom references allow the GC to reclaim objects based on memory capacity.
Why It Matters
Using Weak references prevents metadata structures (like ThreadLocal maps) from causing memory leaks.
Interview Lens
Tests explaining differences between Soft and Weak references, and when each is appropriate.
The Four Reference Types
- Strong Reference: Standard variable assignment (e.g.
Object obj = new Object();). The GC will never collect this object as long as the reference is reachable. - Soft Reference (
SoftReference): Reclaimed only if the JVM desperately needs memory to avoid throwing an OutOfMemoryError. Useful for memory-sensitive caches. - Weak Reference (
WeakReference): Reclaimed immediately on the next GC run, regardless of memory capacity, if the object has no strong references. Used inWeakHashMap. - Phantom Reference (
PhantomReference): Reclaimed after execution of finalize. Used withReferenceQueueto perform post-mortem resource cleanups.
Code Walkthrough
This program demonstrates wrapping objects in weak references and observing garbage collection reclamation.
Interview-Relevant Information
Q: How does WeakHashMap use WeakReference internally?
Answer: WeakHashMap keys are wrapped in `WeakReference`. If a key object is no longer referenced anywhere else in the application, the key is reclaimed by the GC. The map automatically detects this and discards the associated value entry, preventing leaks.
Quick Checklist
What is the difference between Soft and Weak references? How does WeakHashMap prevent leaks? If yes, you understand reference types.
Use Cases
Designing metadata mappings (e.g. associating thread-locals with specific threads).
Implementing memory-sensitive image caches.
Common Mistakes
Using SoftReference for low-latency caches where predictable performance matters (SoftReferences can cause long GC pause times under memory pressure).
Calling weakRef.get() without null-checking, causing NullPointerExceptions if the object was collected.