What are the differences between various types of references in Java and how do they affect garbage collection?
sobes.tech AI
Answer from AI
In Java, there are different types of references that affect the behavior of the garbage collector:
-
Strong Reference — a regular reference to an object. As long as strong references exist, the object will not be garbage collected.
-
Soft Reference — an object with a soft reference is only removed when memory is low. Used for caching.
-
Weak Reference — an object with a weak reference can be garbage collected during the next garbage collection cycle, even if weak references exist.
-
Phantom Reference — used to track when an object is ready to be collected but has not yet been removed. Allows for additional actions after the object is collected.
Example of using a weak reference:
import java.lang.ref.WeakReference;
public class WeakRefExample {
public static void main(String[] args) {
Object obj = new Object();
WeakReference<Object> weakRef = new WeakReference<>(obj);
obj = null; // Remove strong reference
System.gc(); // Run garbage collector
if (weakRef.get() == null) {
System.out.println("Object has been collected");
} else {
System.out.println("Object is still accessible");
}
}
}
Thus, the choice of reference type allows controlling the lifetime of objects and memory usage efficiency.