- finalize() method pre defined method which is present in java.lang.Object class.
- finalize() method is protected method defined in java.lang.Object class.
- The finalize method is a method defined in the Object class in Java. It is called by the garbage collector before an object is garbage collected.
- The finalize method can be overridden in a subclass to perform any cleanup that is required before the object is garbage collected. For example, if an object has opened a file, it may need to close that file in its finalize method.
- protected void finalize() throws Throwable{
- }
1.What is purpose of overriding finalize() method?
- The finalize() method should be overridden for an object to include the clean up code or to dispose of the system resources that should to be done before the object is garbage collected.
2.How many times does the garbage collector calls the finalize() method for an object?
- Only once.
3.What happens if an uncaught exception is thrown from during the execution of finalize() method of an object?
- The exception will be ignored and the garbage collection (finalization) of that object terminates
- If we are overriding finalize() method then its our responsibility to call finalize() method explicitly.
- finalize() method never invoked more than once by JVM or any given object.
- There is no guaranty that if we call finalize() method but we can force garbage collector by calling below two methods
- System.gc();
- Runtime.getRuntime().gc();
#1 : Java program to explain about finalize() method
- package inheritance
- public class B {
- /**
- * Finalize() method in java
- * @author www.instanceofjava.com
- */
- @Override
- protected void finalize() throws Throwable {
- try{
- System.out.println("Inside Finalize() method of Sub Class : B");
- }catch(Throwable t){
- throw t;
- }finally{
- System.out.println("Calling finalize() method of Super Class: Object");
- super.finalize();
- }
- }
- public static void main(String[] args) throws Throwable{
- B obj= new B();
- String str=new String("finalize method in java");
- str=null;
- obj.finalize();
- }
- }
- It is important to note that the finalize method is not guaranteed to be called, and it should not be relied upon for performing important tasks. It is generally better to use try-finally blocks to ensure that resources are properly cleaned up.
No comments