In Java, a weak reference is a type of reference that does not prevent an object from being garbage collected.
✅ In plain terms:
If an object is only weakly referenced (i.e., no strong references point to it), then the GC is free to collect it at any time — even if it’s still “reachable” through that weak reference.
import java.lang.ref.WeakReference;
public class WeakRefExample {
public static void main(String[] args) {
String strong = new String("Hello");
WeakReference<String> weak = new WeakReference<>(strong);
System.out.println("Before GC: " + weak.get()); // "Hello"
strong = null; // Remove strong reference
System.gc(); // Suggest garbage collection
// Wait a bit to give GC a chance
try { Thread.sleep(500); } catch (InterruptedException e) {}
System.out.println("After GC: " + weak.get()); // null (if GC ran)
}
}
📦 Reference Types in Java
Reference Type | GC Behavior | Example Use Case |
---|---|---|
Strong | Never collected unless unreachable | Normal variables |
Weak | Collected as soon as no strong refs | WeakHashMap , caches |
Soft | Collected only when memory is low | Memory-sensitive caches |
Phantom | Used for final cleanup (rare) | Advanced GC tracking |
✅ Use Cases for Weak References
WeakHashMap
:- Keys are weak references.
- When a key is no longer strongly referenced, it’s automatically removed from the map.
- Caches:
- Store data that can be discarded if not in use anymore.
- Avoiding memory leaks:
- When you want to refer to something without preventing it from being garbage collected.
⚠️ Gotchas
- You can’t rely on when the GC will clear weak references.
weakRef.get()
can returnnull
at any time, so always check before using.
🧠 TL;DR:
A weak reference lets you point to an object without preventing it from being garbage collected.
Useful for caches, observers, and memory-sensitive structures.