Soft, Weak, and Phantom References in Java
In Java, objects are normally referenced strongly, meaning they are not eligible for garbage collection as long as a strong reference exists. However, Java provides Soft, Weak, and Phantom references in the java.lang.ref
package, which allow fine-grained control over garbage collection behavior.
1️⃣ Strong References (Default)
What Is a Strong Reference?
- A strong reference is the default type of object reference in Java.
- If an object has a strong reference, it will never be garbage collected until the reference is removed.
Example: Strong Reference (Regular Object)
MyObject obj = new MyObject(); // Strong reference
🔹 The object obj
will not be garbage collected unless explicitly set to null
.
2️⃣ Soft References (SoftReference)
What Is a Soft Reference?
- Soft references allow an object to remain in memory until the JVM runs low on memory.
- If memory is needed, SoftReferences are cleared before an OutOfMemoryError occurs.
- Useful for caching mechanisms where objects should be kept as long as possible, but removed if necessary.
Example: Soft Reference
import java.lang.ref.SoftReference;
public class SoftReferenceExample {
public static void main(String[] args) {
MyObject strongObj = new MyObject();
SoftReference<MyObject> softRef = new SoftReference<>(strongObj);
strongObj = null; // Remove strong reference
// If JVM needs memory, softRef may be cleared
MyObject obj = softRef.get();
if (obj != null) {
System.out.println("Object is still available.");
} else {
System.out.println("Object has been garbage collected.");
}
}
}
When Is a Soft Reference Cleared?
✔ Only when JVM is running out of memory.
✔ Good for caching (e.g., image caches, object pools).
❌ Not reliable for objects that must always be available.
3️⃣ Weak References (WeakReference)
What Is a Weak Reference?
- A weak reference allows an object to be garbage collected as soon as no strong references exist.
- The garbage collector does not wait for memory pressure like in
SoftReference
. - Used for memory-sensitive caches and avoiding memory leaks.
Example: Weak Reference
import java.lang.ref.WeakReference;
public class WeakReferenceExample {
public static void main(String[] args) {
MyObject strongObj = new MyObject();
WeakReference<MyObject> weakRef = new WeakReference<>(strongObj);
strongObj = null; // Remove strong reference
System.gc(); // Suggest garbage collection
if (weakRef.get() != null) {
System.out.println("Object is still available.");
} else {
System.out.println("Object has been garbage collected.");
}
}
}
When Is a Weak Reference Cleared?
✔ As soon as there are no strong references left.
✔ Great for memory-sensitive caches (e.g., WeakHashMap).
❌ Not reliable if the object is needed frequently.
4️⃣ Phantom References (PhantomReference)
What Is a Phantom Reference?
- Phantom references are objects that have already been marked for finalization, but not yet garbage collected.
get()
method always returnsnull
.- Used to perform cleanup operations after GC.
Example: Phantom Reference
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
public class PhantomReferenceExample {
public static void main(String[] args) {
MyObject obj = new MyObject();
ReferenceQueue<MyObject> refQueue = new ReferenceQueue<>();
PhantomReference<MyObject> phantomRef = new PhantomReference<>(obj, refQueue);
obj = null; // Remove strong reference
System.gc(); // Suggest garbage collection
if (phantomRef.get() == null) {
System.out.println("Object is marked for finalization.");
}
}
}
When Is a Phantom Reference Cleared?
✔ Only after the object has been finalized.
✔ Used for post-GC cleanup (e.g., native resource deallocation).
❌ Cannot retrieve the object via get()
.
5️⃣ Summary Table
Reference Type | When Is It Collected? | Use Case |
---|---|---|
Strong Reference | Never (unless set to null ) | Regular objects |
Soft Reference | If memory is low | Caching (retain as long as possible) |
Weak Reference | As soon as no strong references exist | Memory-sensitive caches (WeakHashMap ) |
Phantom Reference | After finalization, before actual GC | Cleanup operations (e.g., native resources) |
6️⃣ Practical Use Cases
🟢 Soft References for Caching
- Store objects that should remain in memory but can be discarded when needed.
- Example: Image cache in a memory-sensitive application.
🟢 Weak References for Avoiding Memory Leaks
- Prevents strong references from keeping objects alive unnecessarily.
- Example: WeakHashMap (stores keys as WeakReferences so they don’t prevent GC).
🟢 Phantom References for Cleanup Tasks
- Used when you need to run cleanup code after an object is garbage collected.
- Example: Cleaning up native resources like file handles or sockets.
7️⃣ Conclusion
- SoftReference: Retains objects until memory is low (best for caching).
- WeakReference: Allows objects to be garbage collected ASAP (best for weak key-value caches).
- PhantomReference: Used for post-GC cleanup (best for resource deallocation).
📌 In short: SoftReference for caching, WeakReference for memory-sensitive caches, and PhantomReference for cleanup tasks! 🚀