Weak Reference and Soft Reference are special types of references in Java that allow the Garbage Collector (GC) to reclaim objects under certain conditions. They are part of the java.lang.ref package and are mainly used for memory-sensitive applications such as caches, memory management utilities, and resource optimization.
Why Do We Need Special References?
Normally, Java uses Strong References.
Employee employee =
new Employee();As long as employee exists, the object cannot be garbage collected.
Reference Types in Java
Strong Reference
Strong Reference
|
|
Object
Soft Reference
Soft Reference
|
|
Object
Weak Reference
Weak Reference
|
|
Object
Soft Reference
A SoftReference allows an object to stay in memory until the JVM requires additional memory.
Suppose an application caches product information.
import java.lang.ref.SoftReference;
public class Demo {
public static void main(String[] args) {
String data =
new String("Cached Data");
SoftReference<String> reference =
new SoftReference<>(data);
data = null;
System.out.println(
reference.get());
}
}Cached Data
The object may remain available until memory pressure occurs.
Weak Reference
A WeakReference allows an object to be garbage collected as soon as no strong references exist.
import java.lang.ref.WeakReference;
public class Demo {
public static void main(String[] args) {
String data =
new String("Temporary Data");
WeakReference<String> reference =
new WeakReference<>(data);
data = null;
System.gc();
System.out.println(
reference.get());
}
}null
The object may be collected immediately after GC runs.
Suppose a web application stores user profile images.
Soft Reference vs Weak Reference
Feature Soft Reference Weak Reference
Garbage Collection When memory is low As soon as object is weakly reachable
Object Lifetime Longer Shorter
Caching Suitability Excellent Limited
Memory Sensitivity High Very High
Typical Usage Caches Lookup tables
Common Real-World Usage
WeakHashMap Example
WeakHashMap internally uses weak references for keys.
This helps prevent memory leaks.
When to Use Which?
A concise interview answer is
SoftReference and WeakReference are special reference types used for memory-sensitive applications. A SoftReference keeps an object alive until the JVM needs memory, making it suitable for caches. A WeakReference allows an object to be garbage collected as soon as no strong references exist, making it useful for lookup tables, WeakHashMap, and preventing memory leaks.
Last updated: 11 November 2026
Previous question: What is reflection in Java?
Next question: What is Java Flight Recorder?