Junior — Middle
Explain what a weak reference is and how it differs from a strong reference in memory management.
sobes.tech AI
Answer from AI
A strong reference is a normal reference to an object in Java. As long as there is at least one strong reference to an object, the garbage collector will not remove this object from memory.
A weak reference is a reference that does not prevent the garbage collector from removing the object. If an object is only accessible through weak references, it is considered a candidate for garbage collection.
An example of using weak references is caching, where objects can be removed when memory is low to avoid holding them in memory constantly.
Code example:
import java.lang.ref.WeakReference;
public class WeakReferenceExample {
public static void main(String[] args) {
Object strong = new Object();
WeakReference<Object> weak = new WeakReference<>(strong);
System.out.println("Before nulling strong: " + weak.get()); // object is accessible
strong = null; // now the object is only accessible through a weak reference
System.gc(); // attempt to invoke garbage collection
System.out.println("After GC: " + weak.get()); // may be null if the object has been collected
}
}