Sub topic 7
Soft, weak, and phantom references
This chapter assumes you know how GC roots and reachability decide whether an object is garbage, which the earlier chapters covered. It also assumes you can read basic generics and try-with-resources code. By the end you should be able to choose between the reference types and avoid the usual mistakes with them.
Why more than one kind of reference
An ordinary reference such as Object o = new Object(); is a strong reference. If a GC root can reach an object through a chain of strong references, the collector must keep it.
Sometimes you want to refer to an object without forcing it to stay alive. Examples are a cache that can be rebuilt, a registry of listeners, or a hook that runs when a native resource owner is gone. The java.lang.ref package supports this with wrapper objects. The wrapper (the Reference object) is strongly reachable. The object inside it, called the referent, is held with a weaker guarantee.
The collector classifies each object by the strongest path that reaches it:
| Reachability | Reached by | What the collector does |
|---|---|---|
| Strongly reachable | A normal reference chain from a root | Keeps it |
| Softly reachable | Only through `SoftReference` objects | Clears them when memory is tight |
| Weakly reachable | Only through `WeakReference` objects | Clears them at the next collection that covers the object |
| Phantom reachable | Only through `PhantomReference` objects, after finalization | Enqueues the reference after the object is unreachable |
Weak references
A WeakReference does not keep its referent alive. When the collector finds that the only paths to an object are weak, it clears the reference. After that, get() returns null.
import java.lang.ref.WeakReference;
public class WeakDemo {
public static void main(String[] args) {
Object payload = new Object();
WeakReference<Object> ref = new WeakReference<>(payload);
System.out.println("Before: " + (ref.get() != null));
payload = null; // remove the only strong reference
System.gc(); // a request, not a guarantee
System.out.println("After: " + ref.get());
}
}On a typical HotSpot run this prints Before: true and After: null. System.gc() is only a hint, so never build program logic that depends on the exact moment of clearing.
A weak reference answers the question "is anyone else still using this object?" Use it when you want to observe an object without extending its life.
WeakHashMap
java.util.WeakHashMap holds its keys through weak references. When a key becomes weakly reachable, the entry is removed on a later access to the map. This suits metadata attached to objects you do not own.
Two gotchas catch people regularly:
- Values are held strongly. If a value refers back to its own key, directly or through a chain, the key is always strongly reachable and the entry never disappears.
- Keys that are never collected make the map act like a plain
HashMap. Interned strings, string literals, and small cachedIntegervalues stay strongly reachable elsewhere, so they are poor keys for this purpose.
Soft references
A SoftReference is cleared only when the JVM needs memory. HotSpot guarantees that all soft references are cleared before it throws OutOfMemoryError. Between "plenty of memory" and "out of memory" the JVM uses a policy. By default, a soft reference that has not been used recently is cleared sooner. The -XX:SoftRefLRUPolicyMSPerMB flag (default 1000) controls this. It allows a soft referent to survive roughly that many milliseconds per megabyte of free heap since its last access.
This makes soft references a natural fit for memory-sensitive caches.
import java.lang.ref.SoftReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public class SoftCache<K, V> {
private final ConcurrentHashMap<K, SoftReference<V>> map = new ConcurrentHashMap<>();
private final Function<K, V> loader;
public SoftCache(Function<K, V> loader) {
this.loader = loader;
}
public V get(K key) {
SoftReference<V> ref = map.get(key);
V value = (ref == null) ? null : ref.get();
if (value == null) { // never loaded, or cleared by the GC
value = loader.apply(key);
map.put(key, new SoftReference<>(value));
}
return value;
}
public static void main(String[] args) {
SoftCache<String, byte[]> cache = new SoftCache<>(k -> new byte[1024]);
System.out.println(cache.get("a").length);
System.out.println(cache.get("a").length);
}
}Always copy ref.get() into a local variable and test that, as the code does. Calling ref.get() twice, once to test and once to use, can return null the second time.
Reference queues
Checking get() == null means polling every reference. A ReferenceQueue lets the collector tell you instead. Pass a queue to the reference constructor. After the GC clears the reference, it appends the Reference object to that queue.
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
public class QueueDemo {
public static void main(String[] args) throws Exception {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Object payload = new Object();
WeakReference<Object> ref = new WeakReference<>(payload, queue);
payload = null;
System.gc();
Reference<?> polled = queue.remove(1000); // wait up to 1 second
System.out.println("Enqueued: " + (polled == ref));
}
}The queue gives you the Reference object, not the referent, which is already gone. If you need to know which resource to clean up, subclass the reference and store extra fields (a key, a file descriptor number) in it. Do not store the referent itself in those fields, since that would make it strongly reachable again.
The reference object must itself stay reachable. If nothing holds the WeakReference, the collector may discard it and it will never be enqueued.
Phantom references
A PhantomReference differs from the others in two ways:
get()always returnsnull. You can never get the object back through it.- It is enqueued only after the object has become phantom reachable. That means the object is unreachable and any finalizer has already run. A
PhantomReferencemust be created with a queue to be useful.
Phantom references exist to signal "this object is really gone, so you can release what it owned" without the problems of finalizers. Finalizers can resurrect an object, run on an unpredictable thread, and delay reclamation by at least one extra GC cycle. In Java 9 and later the collector clears a phantom reference when it enqueues it. In Java 8 you had to call clear() yourself before the memory could be freed.
Cleaner: the practical API
You rarely build phantom-reference loops by hand. Since Java 9, java.lang.ref.Cleaner does it for you. You register an object together with a cleanup action, and the action runs once, either when you call clean() or after the object becomes phantom reachable.
import java.lang.ref.Cleaner;
public class CleanerDemo {
private static final Cleaner CLEANER = Cleaner.create();
// Holds only what cleanup needs. It must NOT reference the Resource.
private static class State implements Runnable {
@Override
public void run() {
System.out.println("Released native handle");
}
}
static class Resource implements AutoCloseable {
private final Cleaner.Cleanable cleanable;
Resource() {
this.cleanable = CLEANER.register(this, new State());
}
@Override
public void close() {
cleanable.clean(); // runs State.run() at most once
}
}
public static void main(String[] args) {
try (Resource r = new Resource()) {
System.out.println("Using resource");
}
}
}Two rules matter here:
- The cleanup action must not capture the object it cleans. If
Statewere an inner class, or a lambda usingthis, it would hold a strong reference to theResource. The object would then never become unreachable, and the cleaner would never fire. - The cleaner is a safety net, not the main mechanism. Close resources explicitly with try-with-resources and use the
Cleanerto catch the cases where callers forget.
Choosing a reference type
| Need | Use | Typical example |
|---|---|---|
| Keep the object normally | Strong reference | Almost all code |
| Cache that may shrink under memory pressure | `SoftReference` | Decoded images, parsed templates |
| Observe or annotate an object without extending its life | `WeakReference`, `WeakHashMap` | Listener registries, per-object metadata |
| Run cleanup after an object is gone | `Cleaner` (built on `PhantomReference`) | Native memory, file handles |
Common errors
- Treating
get()as stable. The referent can vanish between two calls. Copy it to a local variable once. - Strong reference leaks around a weak one. A
WeakReference<Foo>does nothing if a field, a thread-local, or a listener list also holdsFoostrongly. - Weak keys with values that point at the key.
WeakHashMapentries then never expire. - Expecting a reference to be cleared right after
System.gc(). The call is a request. Some JVM flags, such as-XX:+DisableExplicitGC, turn it into a no-op. - Forgetting that wrappers cost memory. Each
SoftReferenceand map entry is itself an object. Millions of tiny cached values can spend more on wrappers than they save. - Using finalizers instead.
finalize()is deprecated. PreferCleaneror try-with-resources.
Exercise
A WeakHashMap<Key, Value> entry never disappears, even after you drop every outside reference to the Key object and run several collections. The Value class has a field Key owner. What is the most likely cause, and how would you fix it?
Show answer
The map holds values strongly, and the value points back to its own key through owner. The key is therefore always strongly reachable through the map's value, so the weak key is never cleared. Fix it by removing the back-reference, or by wrapping the value in a WeakReference (WeakHashMap<Key, WeakReference<Value>>) so the map does not keep the key alive through the value.
Exercise
You write a Cleaner action as a lambda inside the constructor of Resource: CLEANER.register(this, () -> release(handle)), where release is an instance method. The cleanup never runs when the caller forgets to call close(). Why, and how do you fix it?
Show answer
The lambda calls an instance method, so it captures this and keeps the Resource strongly reachable from the cleaner. The object never becomes phantom reachable. Move the data needed for cleanup (such as handle) into a separate static nested class that implements Runnable, and register an instance of that class instead.