What are the four types of references in java.lang.ref (strong, soft, weak, phantom), and how does each affect an object's eligibility for garbage collection?
Short answer
A strong reference (the default, ordinary Java reference) prevents an object from ever being garbage collected as long as it exists; a SoftReference allows the object to be collected, but only when the JVM is under memory pressure (making soft references suitable for…
Advertisement
AModel answer
A strong reference (the default, ordinary Java reference) prevents an object from ever being garbage collected as long as it exists; a SoftReference allows the object to be collected, but only when the JVM is under memory pressure (making soft references suitable for memory-sensitive caches that should hold onto data as long as there's spare memory, but release it before an OutOfMemoryError); a WeakReference allows the object to be collected as soon as no strong references remain, regardless of memory pressure (useful for canonicalizing mappings or metadata that shouldn't itself keep an object alive, like WeakHashMap's keys); a PhantomReference is enqueued only AFTER the object has already been finalized and its memory reclaimed, used for very specific pre-cleanup-action scenarios (like triggering native resource cleanup) rather than accessing the object itself, since get() on a PhantomReference always returns null.
// SoftReference: cache that survives unless memory is genuinely needed elsewhere
Map<String, SoftReference<byte[]>> imageCache = new HashMap<>();
imageCache.put("logo", new SoftReference<>(loadImageBytes("logo.png")));
// WeakReference: doesn't keep the referent alive on its own
WeakReference<LargeObject> weakRef = new WeakReference<>(new LargeObject());
// Once no strong references to the LargeObject remain, it CAN be collected
// even though weakRef itself still technically existsReal-world example
An image-caching layer wraps cached image byte arrays in SoftReference, letting the cache grow generously under normal conditions but automatically shrink (with the JVM reclaiming the soft-referenced image data) rather than throwing an OutOfMemoryError if the application suddenly needs significantly more memory for a memory-intensive operation elsewhere.
Likely follow-ups
- Why does WeakHashMap use weak references specifically for its keys rather than its values?
- What's the practical use case for PhantomReference given get() always returns null on it?
Related topics