Java FAQ: Top Questions
43. What is the WeakReference class in Java?
WeakReference
in
java.lang.ref
is a reference type that allows the referenced object to be garbage-collected if it has no strong references, useful for memory-sensitive applications.
-
Weak Reference:
Created with
new WeakReference<>(obj)
. - Garbage Collection: The object is eligible for GC when only weak references remain.
- ReferenceQueue: Optionally tracks when the object is collected.
- Use Case: Caching, canonicalization, or avoiding memory leaks.
-
Related Types:
SoftReference
(less aggressive),PhantomReference
(post-GC cleanup).