Finalization
- Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
- finalize() method is present in Object class with following prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for perform our cleanup activities like closing connection from database. - The finalize() method called by Garbage Collector not JVM. Although Garbage Collector is one of the module of JVM.
- Object class finalize() method has empty implementation, thus it is recommended to override finalize() method to dispose of system resources or to perform other cleanup.
- The finalize() method is never invoked more than once for any given object.
- If an uncaught exception is thrown by the finalize() method, the exception is ignored and finalization of that object terminates.
// Java program to demonstrate requesting// JVM to run Garbage CollectorpublicclassTest{publicstaticvoidmain(String[] args)throwsInterruptedException{Test t1 =newTest();Test t2 =newTest();// Nullifying the reference variablet1 =null;// requesting JVM for running Garbage CollectorSystem.gc();// Nullifying the reference variablet2 =null;// requesting JVM for running Garbage CollectorRuntime.getRuntime().gc();}@Override// finalize method is called on object once// before garbage collecting itprotectedvoidfinalize()throwsThrowable{System.out.println("Garbage collector called");System.out.println("Object garbage collected : "+this);}}- There is no guarantee that any one of above two methods will definitely run Garbage Collector.
- The call System.gc() is effectively equivalent to the call : Runtime.getRuntime().gc()
Output:Garbage collector called Object garbage collected : Test@46d08f12 Garbage collector called Object garbage collected : Test@481779b8
Note :
Note :
Comments
Post a Comment