Junior
What types of references are there in Java?
sobes.tech AI
Answer from AI
In Java, there are several types of references that affect garbage collection and the lifecycle of objects:
-
Strong Reference — a normal 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 for garbage collection but not yet collected. Allows for additional actions after finalization.
Example of creating a weak reference:
import java.lang.ref.WeakReference;
String strong = new String("Hello");
WeakReference<String> weak = new WeakReference<>(strong);
strong = null; // now the object is only accessible through weak
// during garbage collection, the object may be collected