Junior — Middle
What is the purpose of weak references in programming?
sobes.tech AI
Answer from AI
Weak References in programming are used so that an object can be accessible to the garbage collector even if there is a weak reference to it. This is useful for caching or storing auxiliary data that should not prevent the object from being removed from memory.
In Java, for example, if an object is only accessible through weak references, it will be removed during the next garbage collection cycle. This helps prevent memory leaks when objects are no longer needed but still have references.
Example of using a weak reference in Java:
import java.lang.ref.WeakReference;
public class WeakRefExample {
public static void main(String[] args) {
Object strong = new Object();
WeakReference<Object> weak = new WeakReference<>(strong);
System.out.println("Before nulling strong: " + weak.get());
strong = null; // Remove strong reference
System.gc(); // Request garbage collection
System.out.println("After GC: " + weak.get()); // Might be null
}
}