![]() |
VOOZH | about |
One of the important parts of memory management in Java is, how it handles references to objects and decides when to remove those objects that are no longer needed. Java offers several types of references, and it is important to understand that all references are not the same.
In Java, there are four types of references differentiated by the way in which they are garbage collected.
Prerequisite: Basic understanding of Garbage Collection
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.
MyClass obj = new MyClass ();
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.
๐ Strong References in Java
Example:
Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. ๐ weak-references-in-java
Example:
GeeksforGeeks GeeksforGeeks
Note: The object may be garbage collected anytime after the strong reference is removed.
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. ๐ soft-references-in-java
Example:
GeeksforGeeks GeeksforGeeks
The objects which are being referenced by phantom references are eligible for garbage collection. But, before removing them from the memory, JVM puts them in a queue called โreference queueโ . They are put in a reference queue after calling finalize() method on them.To create such references java.lang.ref.PhantomReference class is used.
Example:
Output: