Strong, soft, weak and phantom references
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A normal variable keeps its object alive for as long as the variable can be used. The classes in java.lang.ref let you point at an object without keeping it alive, so the garbage collector may clear the link when it needs to.
Strong references: the normal kind
A weak reference points to an object without keeping it alive; once only weak references remain, the garbage collector may remove the object.
A strong reference is an ordinary variable, field, array slot or collection entry that points to an object. As long as one strong path leads from a GC root to an object, the garbage collector will never free it, even if memory runs out.
Ticket t = new Ticket("PNR4521"); // t is a strong referenceTicket same = t; // a second strong reference, same objectt = null; // still reachable through 'same'same = null; // no strong path left: eligible for GC
WeakReference<Ticket> w = new WeakReference<>(new Ticket("PNR9999"));Ticket back = w.get(); // the object, or null once it was clearedEvery leak in the previous lesson was made of strong references. The other three kinds, SoftReference, WeakReference and PhantomReference, are objects that hold a reference the collector is allowed to clear. You create them around an object, and read the object back with get().
SoftReference: cleared when memory runs low
A SoftReference keeps its object while memory is comfortable and lets the GC clear it when memory gets tight. The Javadoc gives one firm promise: every softly reachable object is cleared before the JVM throws OutOfMemoryError.
Example 1 · A soft reference survives a GC with plenty of memory
import java.lang.ref.SoftReference;import java.util.ArrayList;import java.util.List;
public class SoftRefDemo { public static void main(String[] args) { // A 10 MB question-paper image, cached only softly. SoftReference<byte[]> paperImage = new SoftReference<>(new byte[10_000_000]);
System.gc(); System.out.println("After a GC with plenty of memory, cached: " + (paperImage.get() != null));
// Now other work needs memory: five 3 MB blocks that must stay. List<byte[]> answerSheets = new ArrayList<>(); for (int i = 0; i < 5; i++) { answerSheets.add(new byte[3_000_000]); } System.out.println("Answer sheets in memory: " + answerSheets.size());
byte[] image = paperImage.get(); if (image != null) { System.out.println("Image still cached: " + image.length + " bytes"); } else { System.out.println("Image was cleared to make room; load it again from disk"); } }}After a GC with plenty of memory, cached: true Answer sheets in memory: 5 Image still cached: 10000000 bytes
What this code does
- With the default heap (a quarter of your RAM on most machines), the 10 MB image survives
System.gc()and the 15 MB of answer sheets, because free memory is plentiful. The read at the end uses the safe pattern:get()once, then anullcheck. - Whether a soft reference is cleared depends on free memory and the JVM's policy, so the result can differ between machines and heap sizes. Example 2 runs the same program with a small heap.
Example 2 · The same program with a 24 MB heap
java -Xmx24m -Xlog:gc SoftRefDemo[0.016s][info][gc] Using G1 [0.092s][info][gc] GC(0) Pause Full (System.gc()) 11M->10M(24M) 3.483ms After a GC with plenty of memory, cached: true ... [0.117s][info][gc] GC(4) Pause Full (G1 Compaction Pause) 19M->19M(24M) 2.331ms ... [0.121s][info][gc] GC(6) Pause Full (G1 Compaction Pause) 22M->12M(24M) 2.818ms ... Answer sheets in memory: 5 Image was cleared to make room; load it again from disk
What this code does
- A real run on HotSpot (JDK 21, G1), with Young and Concurrent lines cut. The first Full GC keeps the image (10M after GC). The answer sheets need 15 MB more, which does not fit next to it in 24 MB.
- The last Full GC frees 10 MB (
22M->12M): the JVM cleared the soft reference instead of throwing OutOfMemoryError, exactly as theSoftReferencecontract promises. The program then seesnulland reloads.
When exactly it is cleared before that is up to the JVM. On HotSpot (Java 17 and 21) the rule is time-based: a soft reference survives a collection if it was used within roughly 1 second per free megabyte of heap (-XX:SoftRefLRUPolicyMSPerMB, default 1000). So with plenty of free memory, recently used soft objects stay; when free memory shrinks, they go. That makes soft references look like a natural memory-sensitive cache, for example decoded images or a question paper loaded from disk. The next lesson explains why such caches often behave badly under load.
WeakReference: cleared once nothing strong remains
A WeakReference does not keep its object alive at all. Once the last strong (and soft) path to the object is gone, the GC clears the weak reference and frees the object the next time it collects the part of the heap that holds it.
Example 3 · A weak reference is cleared once the strong one is gone
import java.lang.ref.WeakReference;
class Ticket { final String pnr;
Ticket(String pnr) { this.pnr = pnr; }}
public class WeakRefDemo { static void gcAndWait() throws InterruptedException { System.gc(); // a request; HotSpot usually runs a full GC here Thread.sleep(100); }
public static void main(String[] args) throws InterruptedException { Ticket ticket = new Ticket("PNR4521"); // strong reference WeakReference<Ticket> weak = new WeakReference<>(ticket);
gcAndWait(); System.out.println("Strong ref still held -> weak.get(): " + weak.get().pnr);
ticket = null; // drop the only strong reference gcAndWait(); Ticket t = weak.get(); System.out.println("Strong ref dropped -> weak.get(): " + (t == null ? "null" : t.pnr)); }}Strong ref still held -> weak.get(): PNR4521 Strong ref dropped -> weak.get(): null
What this code does
- While
ticketstill points to the object,weak.get()returns it even after a GC: a strong path exists. Afterticket = null, the only path left is weak, so the GC clears it andget()returnsnull. System.gc()is only a request, and reference processing happens just after the collection, hence the short sleep. On HotSpot with default settings this prints the lines shown; the exact moment of clearing is not guaranteed.
After that, get() returns null. Weak references are for associating data with an object you do not own without stopping it from dying: a map of extra details per object (WeakHashMap, next lesson), a list of listeners, a canonical copy of a value. They are not caches: a weakly held object usually vanishes at the very next collection.
Predict the output
Is the object still there after a GC?
Read each program and pick what it prints.
Round 1 of 3
A weak reference while a normal variable still holds the invoice.
PhantomReference and ReferenceQueue
A ReferenceQueue is a queue where the JVM puts reference objects after their targets have been collected (or cleared). You pass the queue to the reference's constructor and later call poll() (returns at once, maybe null) or remove(timeout) (waits) to learn which objects are gone.
Example 4 · PhantomReference and ReferenceQueue: learn when an object is gone
import java.lang.ref.PhantomReference;import java.lang.ref.Reference;import java.lang.ref.ReferenceQueue;
class UploadedFile { final String name;
UploadedFile(String name) { this.name = name; }}
// A phantom reference that remembers which file it was for.class FileWatcher extends PhantomReference<UploadedFile> { final String name;
FileWatcher(UploadedFile file, ReferenceQueue<UploadedFile> queue) { super(file, queue); this.name = file.name; // copy the name now: get() will always return null }}
public class ReferenceQueueDemo { public static void main(String[] args) throws InterruptedException { ReferenceQueue<UploadedFile> queue = new ReferenceQueue<>();
UploadedFile resume = new UploadedFile("resume.pdf"); UploadedFile photo = new UploadedFile("photo.jpg"); FileWatcher w1 = new FileWatcher(resume, queue); FileWatcher w2 = new FileWatcher(photo, queue);
System.out.println("get() on a phantom reference: " + w1.get()); System.out.println("Queue before GC: " + queue.poll());
photo = null; // only photo.jpg becomes unreachable System.gc();
Reference<? extends UploadedFile> ref = queue.remove(1000); if (ref != null) { System.out.println("Collected: " + ((FileWatcher) ref).name); } System.out.println("Anything else queued? " + (queue.poll() != null)); System.out.println("resume.pdf still in use: " + resume.name); }}get() on a phantom reference: null Queue before GC: null Collected: photo.jpg Anything else queued? false resume.pdf still in use: resume.pdf
What this code does
get()on a phantom reference is alwaysnull, so the subclass stores the file name when it is created. Before any GC the queue is empty andpoll()returnsnullat once.- After
photo = nulland a GC, the JVM puts the phantom reference forphoto.jpgon the queue, andremove(1000)returns it.resume.pdfis still strongly held, so nothing else is queued.
A PhantomReference is the weakest kind: its get() always returns null, so it can never bring the object back. It is useful only with a queue, as a signal that the object has died and its outside resources, such as a native buffer or a file handle, can now be released. Since Java 9, phantom references are cleared automatically when they are queued, like weak ones. You rarely write phantom code yourself. java.lang.ref.Cleaner, covered two lessons later, is built on phantom references and does the queue work for you.
Checking get() for null
Any call to get() on a soft or weak reference can return null, because the GC may have cleared it at any moment, even between two lines of your code.
Example 5 · Read get() once into a local variable
import java.lang.ref.SoftReference;
class PhotoCache { private SoftReference<String> cached = new SoftReference<>(null); int diskReads = 0;
String photo() { String p = cached.get(); // read once into a local (strong) variable if (p == null) { // cleared by the GC, or never loaded p = loadFromDisk(); cached = new SoftReference<>(p); } return p; }
private String loadFromDisk() { diskReads++; return "photo-of-student-S101"; }
void simulateGc() { cached.clear(); // what the GC does when memory is low }}
public class SafeGetDemo { public static void main(String[] args) { PhotoCache cache = new PhotoCache(); System.out.println(cache.photo() + " (disk reads: " + cache.diskReads + ")"); System.out.println(cache.photo() + " (disk reads: " + cache.diskReads + ")");
cache.simulateGc(); System.out.println(cache.photo() + " (disk reads: " + cache.diskReads + ")"); }}photo-of-student-S101 (disk reads: 1) photo-of-student-S101 (disk reads: 1) photo-of-student-S101 (disk reads: 2)
What this code does
photo()readscached.get()once intop. If it isnull, the photo is loaded and a new soft reference is stored; either way the method returns the strong localp, which cannot disappear.simulateGc()callsclear(), which does exactly what the GC does to a soft reference. The third call notices thenulland reads the disk again:disk reads: 2.
So if (ref.get() != null) use(ref.get()); is a bug: the first call may see the object and the second may see null. The safe pattern is: call get() once, store the result in a local variable, check that local for null, and use only the local. The local is a strong reference, so while you hold it the object cannot be cleared. If it was null, reload the object or report that it is gone. To check whether a reference points at one particular object, Java 16 added ref.refersTo(obj). It answers without creating a new strong reference, and refersTo(null) tells you whether the reference was cleared.
Next step
Check your understanding
12 quick questions