Sub topic 7
Soft, weak, and phantom references
Prerequisites
This chapter assumes that you know Java objects are accessed through references and that the garbage collector (GC) reclaims objects that the running program can no longer reach. A reference object is a special object from java.lang.ref that gives the GC permission to treat its referent, the object it points to, differently from an ordinary reference.
Why special references exist
An ordinary object reference is a strong reference:
Object value = new Object();As long as value can be reached from a GC root, the object must remain alive. GC roots include active stack variables, static fields, and running threads.
Soft, weak, and phantom references let you keep a relationship with an object without keeping that object alive in the same way.
| Reference type | Can `get()` return the object? | Typical use | Collection behavior |
|---|---|---|---|
| Soft | Yes | Memory-sensitive caches | Usually cleared when memory is needed |
| Weak | Yes, until collection | Canonical maps and listeners | Cleared during a suitable GC |
| Phantom | No | Cleanup notification | Enqueued after finalization and before reclamation |
Soft references for memory-sensitive caches
A SoftReference<T> may be cleared when the JVM needs memory. Until then, get() can return the referent.
import java.lang.ref.SoftReference;
public class ReferenceKinds {
public static void main(String[] args) {
byte[] data = new byte[1024 * 1024];
SoftReference<byte[]> soft = new SoftReference<>(data);
data = null;
byte[] cached = soft.get();
if (cached != null) {
System.out.println("The cached value is still available");
} else {
System.out.println("The cached value was cleared");
}
}
}Soft references can reduce the cost of rebuilding cached data, but they do not provide predictable cache behavior. The JVM decides when to clear them. For a cache with a size limit, expiration policy, or hit-rate requirement, an explicit cache is usually easier to operate.
Weak references and reachability
A WeakReference<T> does not keep its referent alive. When no strong or soft path reaches the object, the GC can clear the weak reference.
Weak references are useful when the reference should not control the object's lifetime. Examples include metadata associated with objects, canonicalization tables, and listener registrations that should disappear when the listener is otherwise unused.
A weak reference can become empty between calls to get(). Therefore, copy the result into a strong local variable before using it:
Object value = weakReference.get();
if (value != null) {
use(value);
}Calling get() twice can produce two different results if collection happens between the calls.
Phantom references and cleanup queues
A PhantomReference<T> always returns null from get(). It is used with a ReferenceQueue<T> to learn that an object is no longer normally reachable.
The queue receives the phantom reference after the referent has become unreachable and the JVM has processed its finalization state. A cleanup thread can remove references from the queue and release associated resources.
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
public class PhantomDemo {
public static void main(String[] args) throws InterruptedException {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Object resourceOwner = new Object();
PhantomReference<Object> phantom =
new PhantomReference<>(resourceOwner, queue);
System.out.println("get(): " + phantom.get()); // always null
resourceOwner = null;
System.gc(); // only a request; processing is not guaranteed
PhantomReference<?> queued =
(PhantomReference<?>) queue.remove(1000);
if (queued != null) {
System.out.println("The referent became phantom reachable");
queued.clear();
} else {
System.out.println("No notification arrived during the wait");
}
}
}Do not use phantom references as a replacement for try-with-resources. Files, sockets, and other scarce resources should be closed explicitly. Phantom references are a fallback notification mechanism when an object owns cleanup state that cannot be handled directly.
Reference queues and common errors
A ReferenceQueue lets an application receive cleared weak or soft references, and enqueued phantom references. The queue contains the reference object, not the referent. Applications often attach a key or cleanup action to a custom reference subclass so the cleanup thread knows what to remove.
Common errors include:
- Storing the referent in another field of a custom reference, which accidentally creates a strong reference.
- Assuming a soft reference is a guaranteed cache entry.
- Using a weak reference when the operation needs the object to remain alive.
- Performing cleanup in a finalizer instead of using explicit resource management.
- Forgetting to process a reference queue, causing reference objects and their metadata to accumulate.
- Treating
nullfromget()as an exceptional event rather than the expected result for a cleared or phantom reference.
The choice depends on the ownership rule. Use a soft reference when losing the value is acceptable and rebuilding it is possible. Use a weak reference when an association must not extend the target's lifetime. Use a phantom reference when you need post-reachability notification without access to the reclaimed object.
Exercise
Which reference type should you choose for a map of metadata that must disappear when the key object is no longer used elsewhere?
Show answer
Use a weak reference, often through a weak-key map such as WeakHashMap, because the metadata association should not keep the key alive.