Junior — Middle
What types of links are used in Java?
sobes.tech AI
Answer from AI
In Java, there are several types of references that manage the lifetime of objects and their garbage collection:
-
Strong Reference — a normal reference to an object. As long as strong references exist, the object will not be garbage collected.
-
Soft Reference — used for caching. An object with a soft reference will only be removed when the memory is low.
-
Weak Reference — an object with such a reference can be garbage collected in the next garbage collection cycle, even if the reference still exists.
-
Phantom Reference — used to track when an object is ready to be collected but has not yet been removed.
Example of using a weak reference:
WeakReference<MyObject> weakRef = new WeakReference<>(new MyObject());
MyObject obj = weakRef.get();
if (obj != null) {
// object is still accessible
} else {
// object has been garbage collected
}