Types of References in Java: Garbage Collection
Types of References in Java: Garbage Collection
In Java there are four types of references differentiated on the way by which they are garbage
collected.
1. Strong References
2. Weak References
3. Soft References
4. Phantom References
Strong References: This is the default type/class of Reference Object. Any object
which has an active strong reference are not eligible for garbage collection. The object is
garbage collected only when the variable which was strongly referenced points to null.
Here ‘obj’ object is strong reference to newly created instance of MyClass, currently obj
is active object so can’t be garbage collected.
obj = null;
//'obj' object is no longer referencing to the instance.
So the 'MyClass type object is now available for garbage collection.
filter_none
edit
play_arrow
brightness_4
Weak References: Weak Reference Objects are not the default type/class of
Reference Object and they should be explicitly specified while using them.
o If JVM detects an object with only weak references (i.e. no strong or soft
references linked to any object object), this object will be marked for garbage
collection.
edit
play_arrow
brightness_4
g.x();
}
}
Output:
GeeksforGeeks
GeeksforGeeks
Soft References: In Soft reference, even if the object is free for garbage
collection then also its not garbage collected, until JVM is in need of memory badly.The
objects gets cleared from the memory when JVM runs out of memory.To create such
references java.lang.ref.SoftReference class is used.
filter_none
edit
play_arrow
brightness_4
g.x();
}
}
Output:
GeeksforGeeks
GeeksforGeeks
filter_none
edit
play_arrow
brightness_4
Runtime Error:
Output:
GeeksforGeeks