Fundamentals 9 min read

Four Types of References in Java and Their Usage

This article explains Java's four reference types—strong, soft, weak, and phantom—detailing their purposes, behavior during garbage collection, and practical code examples that demonstrate how each reference influences object lifecycle and memory management.

IT Xianyu
IT Xianyu
IT Xianyu
Four Types of References in Java and Their Usage

Java provides four kinds of reference types—strong, soft, weak, and phantom—to give developers control over object lifecycles and memory reclamation. The JVM decides whether an object can be reclaimed based on reachability analysis, and these references let programmers influence that process.

Strong Reference

A strong reference is the default; any object referenced strongly will never be collected, even under low‑memory conditions, and the JVM will throw an OOM error instead. Example:

Object o = new Object();
o = null;

When the strong reference is set to null and System.gc() is invoked, the object becomes eligible for collection. The following demo shows a class overriding finalize() to print a message when reclaimed:

public class Student {
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Student 被回收了");
    }
}

public static void main(String[] args) {
    Student student = new Student();
    student = null;
    System.gc();
}

Running this prints "Student 被回收了", confirming the object was collected.

Soft Reference

Soft references are useful for caches. The object is kept as long as memory is sufficient; it is reclaimed only when the JVM needs memory. Example:

SoftReference
studentSoftReference = new SoftReference<>(new Student());
Student student = studentSoftReference.get();
System.out.println(student);

For larger data:

SoftReference
softReference = new SoftReference<>(new byte[1024 * 1024 * 10]);
System.out.println(softReference.get());
System.gc();
System.out.println(softReference.get());
byte[] bytes = new byte[1024 * 1024 * 10];
System.out.println(softReference.get());

The first System.out.println shows the byte array is still alive; after allocating another 10 MB, the soft‑referenced array is cleared, demonstrating its memory‑sensitive behavior.

Weak Reference

Weak references are cleared on any garbage‑collection cycle, regardless of memory pressure. Example:

WeakReference
weakReference = new WeakReference<>(new byte[1]);
System.out.println(weakReference.get());
System.gc();
System.out.println(weakReference.get());

The output shows the reference becomes null after GC, which is why weak references are used in structures like ThreadLocal and WeakHashMap .

Phantom Reference

Phantom references cannot retrieve the referent (their get() always returns null ) and must be paired with a ReferenceQueue . When the GC determines an object is phantom‑referenced, it enqueues the reference before final reclamation. Example:

ReferenceQueue queue = new ReferenceQueue();
PhantomReference
reference = new PhantomReference<>(new byte[1], queue);
System.out.println(reference.get()); // always null

A more complete demo creates a phantom reference to a Student object, starts a thread that fills memory to trigger GC, and another thread that polls the queue to report when the phantom reference is enqueued:

ReferenceQueue queue = new ReferenceQueue();
PhantomReference
reference = new PhantomReference<>(new Student(), queue);
new Thread(() -> {
    for (int i = 0; i < 100; i++) {
        // allocate memory to force GC
    }
}).start();
new Thread(() -> {
    while (true) {
        Reference
r = queue.poll();
        if (r != null) {
            System.out.println("虚引用被回收了:" + r);
        }
    }
}).start();

The output shows "Student 被回收了" followed by a message that the phantom reference was reclaimed, illustrating how phantom references can be used for cleanup tasks such as managing off‑heap memory in NIO.

In summary, strong, soft, weak, and phantom references each serve distinct purposes in Java's memory management strategy, allowing developers to fine‑tune object lifetimes, implement caches, and perform post‑collection cleanup.

JavaMemory ManagementGarbage CollectionWeakReferenceReference TypesPhantomReferenceSoftReference
IT Xianyu
Written by

IT Xianyu

We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.