Junior — Middle
Can you explain what a soft reference is in the context of memory management in Java?
sobes.tech AI
Answer from AI
A SoftReference in Java is a type of reference that allows an object to be garbage collected if the system runs low on memory, but the object is retained as long as there is enough memory.
This is useful for caching: objects with soft references are not immediately removed, only when necessary to free memory.
Example of using a soft reference:
import java.lang.ref.SoftReference;
public class SoftReferenceExample {
public static void main(String[] args) {
Object strongRef = new Object();
SoftReference<Object> softRef = new SoftReference<>(strongRef);
strongRef = null; // now the object is only accessible through the soft reference
Object obj = softRef.get();
if (obj != null) {
System.out.println("Object is accessible");
} else {
System.out.println("Object has been garbage collected");
}
}
}