Junior — Middle
Can you list the types of links that exist in Java and their features?
sobes.tech AI
Answer from AI
In Java, there are the following types of references that affect garbage collection and memory management:
-
Strong Reference
- The default type of reference.
- An object with a strong reference will not be collected by the garbage collector.
-
Soft Reference
- Used for caching.
- Softly referenced objects are only collected when memory is low.
- Class:
java.lang.ref.SoftReference
-
Weak Reference
- Weakly referenced objects are collected during the next garbage collection cycle if there are no strong references.
- Used for implementing weak caches.
- Class:
java.lang.ref.WeakReference
-
Phantom Reference
- Used to track when an object is about to be finalized.
- Cannot be accessed through
get()(returns null). - Used for more fine-grained resource cleanup.
- Class:
java.lang.ref.PhantomReference
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 via the weak reference
String value = weak.get(); // may return null if the object has been collected