Overview
JVM will reclaim the unused object from heap memory for future use.Unused Object means no longer referenced by any part of your program pointer to that object. To demonstrate unused object is reclaim by garbage collector by calling System.gc() function.System.gc() method provides just a "hint" to the JVM that garbage collection should run. But It is not guaranteed!!Parent object set to null
If an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.Below Example - Garbage Collector will call when parent object references set to null
class EligibleParent{ protected void finalize(){ System.out.println("Parent Unused Object is reclaim by Garbage Collector."); } } class EligibleChild extends EligibleParent{ protected void finalize(){ System.out.println("Child Unused Object is reclaim by Garbage Collector."); } } public class EligibleParentNull { public static void main(String[] args) { EligibleParent obj = new EligibleChild(); obj = null; System.gc(); } } |
Output
Child Unused Object is reclaim by Garbage Collector. |
Explanation
Above example System.gc() function is called after obj object set to null.Container object obj is null then contained object automatically becomes eligible for garbage collection.So the child class finalize method is called.Note : Output Order may change based on System.gc() function calling the finalize method.
0 comments:
Post a Comment