Types of References in Java
Java provides four types of references, each defining how the Garbage Collector treats an object. These reference types help developers optimize memory usage, caching, and cleanup operations.

1. Strong Reference (Default)
This is the normal reference type used in Java.
String name = new String("Java");
- GC never removes objects with strong references.
- Object is only removed when reference becomes null or goes out of scope.
- Most common type of reference.
Use Case:
All regular object usage.
2. Soft Reference (Memory-Sensitive Caching)
Soft references are cleared only when JVM is low on memory.
SoftReference<String> softRef =
new SoftReference<>(new String("Data"));
Key Points:
- Ideal for caches (image cache, page cache).
- Survives several GC cycles.
- Cleared only when memory is almost full.
Use Cases:
- In-memory caching systems
- Web page cache
- Objects that are expensive to recreate
3. Weak Reference (Collected Immediately on Next GC)
Objects referenced only through weak references are removed in the next GC cycle.
WeakReference<String> weakRef =
new WeakReference<>(new String("Hello"));
Key Points:
- Does not survive GC.
- Used when object should not block GC.
- Backbone of WeakHashMap.
Use Cases:
- WeakHashMap (auto-removal of keys)
- Metadata, plugin systems
- Listeners that should not prevent GC
4. Phantom Reference (For Post-GC Cleanup)
Phantom references are used to track when an object has been collected.
ReferenceQueue<Object> queue = new ReferenceQueue<>();
PhantomReference<Object> phantomRef =
new PhantomReference<>(new Object(), queue);
Key Points:
- Object is already collected before phantom reference is enqueued.
- You cannot access the object.
- Replacement for deprecated finalization.
- Used for native resource cleanup.
Use Cases:
- DirectByteBuffer cleanup
- Native resource deallocation
- Tracking object lifecycle
Summary Table
| Reference Type | Collected by GC? | When Collected | Common Use Case |
|---|---|---|---|
| Strong | No | Never (until reference removed) | Normal object usage |
| Soft | Yes | Low memory | Caching |
| Weak | Yes | Immediately on GC | WeakHashMap |
| Phantom | Yes (but tracked) | After finalization | Cleanup + native resources |
