Reference types
A normal variable is a strong reference: as long as it exists, its object stays in memory. The java.lang.ref package adds three weaker kinds that let the garbage collector reclaim an object while you still hold a link to it. This page explains the reachability levels, shows how each kind behaves when the collector runs, measures when soft references are cleared, builds a cache that cleans itself through a reference queue, and runs the traps.
Contents
Reachability and the four strengths
The garbage collector keeps every object that can be reached from a root: local variables of running methods, static fields, and a few JVM internals. An ordinary reference is strong; an object reachable through a chain of strong references is never collected. The java.lang.ref
- Strongly reachable: reachable without going through any reference object. Such an object is never collected.
- Softly reachable: reachable only through a
. Kept as long as memory allows; all such objects are guaranteed to be cleared before the JVM throwsSoftReference .OutOfMemoryError - Weakly reachable: reachable only through a
. Cleared at the next collection that finds it.WeakReference - Phantom reachable: already finalized or unreachable, but a
still tracks it.PhantomReference always returnsget() ; the reference exists only to learn that the object is gone.null
When a reference is cleared, it can be added to a ReferenceQueue
| Type | Since | Cleared | get() | Best for |
|---|---|---|---|---|
SoftReference | Java 1.2 | When memory runs low, oldest-used first | Referent until cleared | Memory-sensitive caches, with care |
WeakReference | Java 1.2 | At the next collection | Referent until cleared | Metadata attached to objects you do not own; canonical maps |
PhantomReference | Java 1.2 | After the object is unreachable | Always null | Cleanup after an object is gone; the basis of Cleaner |
WeakHashMap | Java 1.2 | Entries go when their key is weakly reachable | Not applicable | Per-object data keyed by objects you do not own |
Reference.refersTo | Java 16 | Not applicable | Tests the referent without a strong copy | Checks that must not keep the object alive |
Two details changed over time. Since Java 9, a phantom reference is cleared automatically when it is enqueued, like the other kinds; before that, the referent's memory stayed allocated until the program cleared the reference itself. And every reference object costs the collector work: it must discover, process and possibly enqueue each one during a collection, so an application holding millions of weak or soft references spends noticeably longer in garbage collection. Use them for a few thousand cached or attached objects, not as a general-purpose memory management tool.
The programs ran on JDK 21 with the default G1 collector unless noted. They call System.gc()
The four strengths under a collection
One object of each strength is created, with the weak and phantom references registered on a queue, and then garbage collection runs.
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class FourStrengths {
static void gc() throws InterruptedException {
for (int i = 0; i < 5; i++) {
System.gc();
Thread.sleep(50);
}
}
public static void main(String[] args) throws InterruptedException {
ReferenceQueue<Object> queue = new ReferenceQueue<>();
Object strongObj = new Object();
WeakReference<Object> weak = new WeakReference<>(new Object(), queue);
SoftReference<byte[]> soft = new SoftReference<>(new byte[1024]);
PhantomReference<Object> phantom = new PhantomReference<>(new Object(), queue);
System.out.println("before GC: weak alive=" + (weak.get() != null)
+ ", soft alive=" + (soft.get() != null) + ", phantom.get()=" + phantom.get());
gc();
System.out.println("after GC: weak alive=" + (weak.get() != null)
+ ", soft alive=" + (soft.get() != null));
List<String> enqueued = new ArrayList<>();
Reference<?> r;
while ((r = queue.poll()) != null) {
enqueued.add(r.getClass().getSimpleName());
}
Collections.sort(enqueued); // the queue order is not specified
System.out.println("enqueued: " + enqueued);
System.out.println("strong reference still usable: " + (strongObj != null));
}
}
Output:
before GC: weak alive=true, soft alive=true, phantom.get()=null
after GC: weak alive=false, soft alive=true
enqueued: [PhantomReference, WeakReference]
strong reference still usable: true
- Before the collection, the weak and soft referents were alive, and
returnedphantom.get() , as it always does.null - After the collection, the weak referent was gone and the soft referent was still there: there was plenty of free memory, so the collector had no reason to clear it.
- Both the weak and the phantom reference were placed on the queue, telling the program that their objects were collected. The order in which references arrive is not specified, so the program sorts the names.
- The strongly referenced object was never at risk. Most code needs nothing else; the weaker kinds are for the special cases below.
Soft references under memory pressure
Twenty 1 MB arrays are cached through soft references in a JVM limited to 64 MB of heap. After a normal collection the program fills the heap until it runs out, to show the guarantee that soft references are cleared before OutOfMemoryError
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SoftCache {
static final Map<Integer, SoftReference<byte[]>> CACHE = new HashMap<>();
static int cachedEntries() {
int alive = 0;
for (SoftReference<byte[]> ref : CACHE.values()) {
if (ref.get() != null) {
alive++;
}
}
return alive;
}
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
CACHE.put(i, new SoftReference<>(new byte[1024 * 1024])); // 20 x 1 MB
}
System.gc();
System.out.println("after a normal GC, entries still cached: " + cachedEntries());
// Create memory pressure: soft references must be cleared before OutOfMemoryError
List<byte[]> pressure = new ArrayList<>();
try {
while (true) {
pressure.add(new byte[1024 * 1024]);
}
} catch (OutOfMemoryError e) {
int held = pressure.size();
pressure.clear();
System.out.println("under memory pressure, entries still cached: " + cachedEntries());
System.out.println("the loop held more than 40 MB before running out: " + (held > 40));
}
}
}
Output (run with -Xmx64m -XX:+UseSerialGC
after a normal GC, entries still cached: 20
under memory pressure, entries still cached: 0
the loop held more than 40 MB before running out: true
- A normal collection kept all 20 entries. Under pressure, all 20 were cleared before the error, which let the allocation loop get further than 40 MB of a 64 MB heap.
- That is also the problem with soft caches: they are cleared all at once, exactly when the application is short of memory, and until then they make the heap look full, which pushes the collector into more frequent and longer collections. A bounded cache with an explicit size limit and eviction policy is usually more predictable.
When the collector is not desperate, HotSpot decides which soft references to clear with a time-based rule: a softly reachable object survives for -XX:SoftRefLRUPolicyMSPerMBget()refersTo(null)get()
import java.lang.ref.SoftReference;
public class SoftPolicy {
public static void main(String[] args) throws InterruptedException {
SoftReference<byte[]> soft = new SoftReference<>(new byte[1 << 20]);
for (int gc = 1; gc <= 3; gc++) {
Thread.sleep(100);
System.gc();
System.out.println("policy " + System.getProperty("policy") + " ms/MB, after GC " + gc
+ ": soft reference alive = " + !soft.refersTo(null));
}
}
}
Output with the default policy:
policy 1000 ms/MB, after GC 1: soft reference alive = true
policy 1000 ms/MB, after GC 2: soft reference alive = true
policy 1000 ms/MB, after GC 3: soft reference alive = true
Output with -XX:SoftRefLRUPolicyMSPerMB=0
policy 0 ms/MB, after GC 1: soft reference alive = true
policy 0 ms/MB, after GC 2: soft reference alive = false
policy 0 ms/MB, after GC 3: soft reference alive = false
With the default, the reference survived three full collections, because with hundreds of megabytes free it is allowed to live for minutes. With the policy at 0 it was cleared at the second collection: the collector's clock is updated at each collection, so after one more collection the reference was older than the allowed 0 ms. Setting the flag to 0 makes soft references behave almost like weak ones, which some services do on purpose to stop soft caches from filling the heap.
A cache that cleans itself through a reference queue
Weak references to values need cleanup too: once a value is collected, its map entry is a dead object holding a null reference. A reference queue tells the map which entries to remove. Ten values of 100 KB are cached, and the application still holds 3 of them strongly.
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class WeakValueCache {
// Each entry remembers its key, so the queue tells us which map entry to remove
static final class Entry extends WeakReference<byte[]> {
final int key;
Entry(int key, byte[] value, ReferenceQueue<byte[]> queue) {
super(value, queue);
this.key = key;
}
}
final Map<Integer, Entry> map = new HashMap<>();
final ReferenceQueue<byte[]> queue = new ReferenceQueue<>();
void put(int key, byte[] value) {
expunge();
map.put(key, new Entry(key, value, queue));
}
byte[] get(int key) {
expunge();
Entry e = map.get(key);
return e == null ? null : e.get(); // may be null if just collected
}
// Removes entries whose values the GC has cleared
int expunge() {
int removed = 0;
Reference<? extends byte[]> r;
while ((r = queue.poll()) != null) {
Entry e = (Entry) r;
if (map.get(e.key) == e) { // only if not replaced since
map.remove(e.key);
removed++;
}
}
return removed;
}
public static void main(String[] args) throws InterruptedException {
WeakValueCache cache = new WeakValueCache();
byte[][] inUse = new byte[3][]; // the application still uses 3 values
for (int i = 0; i < 10; i++) {
byte[] value = new byte[100000];
cache.put(i, value);
if (i < 3) {
inUse[i] = value;
}
}
System.out.println("entries before GC: " + cache.map.size());
for (int i = 0; i < 5; i++) {
System.gc();
Thread.sleep(50);
}
int removed = cache.expunge();
System.out.println("expunged after GC: " + removed + ", entries left: " + cache.map.size()
+ " " + cache.map.keySet());
System.out.println("get(0) still works: " + (cache.get(0) == inUse[0]));
System.out.println("get(7) after collection: " + cache.get(7));
}
}
Output:
entries before GC: 10
expunged after GC: 7, entries left: 3 [0, 1, 2]
get(0) still works: true
get(7) after collection: null
- After the collection, the 7 values nobody else referenced were cleared, their
references were queued, andEntry removed exactly those keys. The 3 values the application still held, keys 0 to 2, stayed cached.expunge() - Subclassing
to carry the key is the standard technique: the queue hands back the reference object, and the key in it says which entry to remove.WeakReference does the same internally, but for weak keys.WeakHashMap - The check
prevents removing a newer entry that was put under the same key after the old value died.map.get(e.key) == e returnedget(7) : callers of a weak or soft cache must always handle a miss and recompute the value.null
Reference traps
Reference objects follow simple rules, but the consequences are easy to overlook. Each trap below runs a collection and prints what survived.
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
public class ReferenceTraps {
static void gc() throws InterruptedException {
for (int i = 0; i < 5; i++) {
System.gc();
Thread.sleep(50);
}
}
record Listener(String name) { }
public static void main(String[] args) throws InterruptedException {
// 1. A Reference object that is itself garbage is never enqueued
ReferenceQueue<Object> queue = new ReferenceQueue<>();
new PhantomReference<>(new Object(), queue); // reference not kept
PhantomReference<Object> kept = new PhantomReference<>(new Object(), queue);
gc();
int count = 0;
while (queue.poll() != null) {
count++;
}
System.out.println("1. two phantom references created, enqueued: " + count
+ " (only the one we kept: " + (kept != null) + ")");
// 2. Check-then-use: the referent can vanish between two get() calls
WeakReference<StringBuilder> ref = new WeakReference<>(new StringBuilder("data"));
StringBuilder local = ref.get(); // take one strong copy
gc();
System.out.println("2. local copy keeps it alive: " + (ref.get() != null)
+ ", value " + local);
local = null;
gc();
System.out.println("2. after the local is dropped: ref.get() = " + ref.get());
// 3. WeakHashMap: a value that refers to its own key keeps the entry forever
Map<Object, Object> registry = new WeakHashMap<>();
Object owner1 = new Object();
Object owner2 = new Object();
registry.put(owner1, new Listener("plain"));
registry.put(owner2, new Object[] {owner2}); // value points back at key
owner1 = null;
owner2 = null;
gc();
System.out.println("3. WeakHashMap entries after both keys were dropped: "
+ registry.size() + " (the self-referencing one stays)");
}
}
Output:
1. two phantom references created, enqueued: 1 (only the one we kept: true)
2. local copy keeps it alive: true, value data
2. after the local is dropped: ref.get() = null
3. WeakHashMap entries after both keys were dropped: 1 (the self-referencing one stays)
- Two phantom references were created, but only one was enqueued: the program did not keep the first reference object, so it became garbage itself and was never processed. Code that registers references must hold on to them, usually in a set, until they come off the queue;
does this for you.Cleaner - Calling
twice, once to test and once to use, can see the object in the first call andref.get() in the second. Take one strong local copy and use only that; while the local exists, the referent cannot be collected. Once the local was dropped, the referent was gone.null - A
holds its values strongly. The entry whose value pointed back at its own key kept that key strongly reachable, so it was never removed, while the plain entry disappeared. Listener registries keyed by owner objects leak this way. Store aWeakHashMap in the value, or make sure values do not refer to their keys; seeWeakReferenceWeakHashMap .
One more trap needs no program of its own: a weak reference to an object that something else keeps alive is never cleared. A separate test, with five collections, left new WeakReference<>("literal")new WeakReference<>(Integer.valueOf(100))IntegerIntegernew String("fresh")Integer.valueOf(100000)
Choosing a reference type
| Need | Use |
|---|---|
| A normal object you use | A strong reference |
| A cache with predictable memory use | A bounded cache with explicit eviction, not soft references |
| A cache that may shrink under memory pressure | SoftReference |
| Extra data attached to objects you do not control | WeakHashMap |
| A map whose values may be collected | WeakReferenceReferenceQueue |
| Releasing native resources after an object is gone | |
| Test whether a referent is alive without reviving it | refersTo(null) |
For how and when collections run, see