Garbage Collection is a process to clean all the unreferenced objects. Garbage Collector call's protected void finalize() method of Object Class before cleaning every garbaged Object to release non-java resources such as file handle or database connection held by that object.
Interesting fact about Garbage Collector:
public class Test{ public static void main(String[] args) throws InterruptedException { String str = new String("Oshin Talreja"); Test test = new Test(); // making str eligible for gc str = null; // calling garbage collector System.gc(); // waiting for gc to complete Thread.sleep(1000); System.out.println("end of main"); } @Override protected void finalize() { System.out.println("finalize method called"); }} |
OUTPUT:
finalize method called
end of main
Wonder Why Finalize method called once when two object were garbage collected.
Explanation:
Garbage Collector is called for two objects one is String and second is Test. Therefore, finalize() method of String class(if overridden in String class) is called on str. If a class doesn’t override finalize method, then by default Object class finalize() method is called and Object Class Finalize method has an Empty implementation.
Hence, In Output we can read only one call of Finalize method which is for Test object not for String.
Hence, In Output we can read only one call of Finalize method which is for Test object not for String.
For any suggestion or doubts, please comment below :)
No comments:
Post a Comment