Junior — Middle
In what situations are weak references used in programming?
sobes.tech AI
Answer from AI
Weak references in Java are used to refer to objects without preventing their garbage collection. This is useful in the following situations:
- Caching: objects are cached using weak references so they can be removed when memory is low.
- Avoiding memory leaks: when you need to refer to an object but do not want to keep it in memory longer than necessary.
- Listeners and callbacks: to avoid cyclic references that hinder garbage collection.
Example of using a weak reference:
import java.lang.ref.WeakReference;
Object strongRef = new Object();
WeakReference<Object> weakRef = new WeakReference<>(strongRef);
strongRef = null; // now the object is only accessible through weakRef
// The object can be garbage collected if there are no strong references