Java finalize() Method Example

finalize() method in Java is called by the garbage collector it gives the last chance to objects for performing its clean up operation.

Java finalize() Method Example

finalize() method in Java is called by the garbage collector it gives the last chance to objects for performing its clean up operation.

Java finalize() Method Example

Java finalize() Method Example

In this section we will read about the finalize() method. We will read how the finalize() method may used in the programming, why finalize() method is declared as protected and many more things.

finalize() method is a protected method of java.lang.Object class so that the finalize() method can be overridden by all classes. This method is defined as protected to apply the encapsulation feature i.e. to hide the internal process of cleaning up operation and to make available for the subclasses to override inside their body. If this method was defined as private, the encapsulation feature will be applied on it but after that it can't be override by the subclasses.

There is a way of guaranteed calling of finalize() method by JVM on all object which are eligible for garbage collection is to call the System.runFinalization() and Runtime.getRuntime().runFinalization(). In programming the finalize() method can be override into the subclass but, this method is not chained like a constructor so, it is the responsibility of programmer to call the finalize() method of super class because it is not called itself. The best way is to call the finalize() method of super class inside the finally block.

finalize() method should be used where it is required to release the resource like a Java class that holds the I/O devices and required to release after completing their tasks, a Java class where the JDBC connection is made and required to release the resource after completing of process. In such type of programming it is recommended that use the provided close() methods because, there is no guarantee of running of finalize() method in code.

Garbage Collection thread calls the finalize before collecting object and determines the object has no more references. The GC thread calls the finalize only once.

Following code snippet demonstrate you how the finalize() method can be override.

 protected void finalize() throws Throwable {
        try{
            //code for releaseing resources, cleanup operation;
        }catch(Throwable t){
            throw t;
        }finally{
            super.finalize();
        }
     
    }    

Syntax :

protected void finalize() throws Throwable

Example

Here an example is being given which will demonstrate you about how the finalize() method may override and use inside the class. In this example we have created a Java class named ReadFile.java and then created a method for reading a file. In this class I have also overridden the finalize() method and write the code inside it for releasing resources. Then I have created the main method for executing the class. Inside the main method I have created the object of ReadFile class and called the method readFile() for reading file and finalize() for releasing the resources.

ReadFile.java

import java.io.*;
public class ReadFile {

	FileInputStream fis = null;
	File file = null;
	public void readFile()
	{
		file = new File("C:\\Documents and Settings\\bharat\\Desktop\\bipul\\a.txt");
		try
		{
			fis = new FileInputStream(file);			
			int r ;
			System.out.print("File Text : ");
			while ((r = fis.read()) != -1) {				
				System.out.print((char) r);				
			}
			System.out.println();
		}
		catch(FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch(IOException ioe)
		{
			ioe.printStackTrace();
		}
	}
		
 @Override
  protected void finalize() throws Throwable {
    try{
         System.out.println("Calling finalize of Sub Class....");
            if(fis != null)
            {
            	System.out.println("Releasing I/O resource....");
            	fis.close();
            }            
        }catch(Throwable t){
            throw t;
        }finally{
            System.out.println("Calling finalize of Super Class....");
            super.finalize();
        }
    }
 
	public static void main(String args[])
	{
	  ReadFile rf = new ReadFile();
	  rf.readFile();
	  try {
		rf.finalize();
	} catch (Throwable e) {		
		e.printStackTrace();
	}
	}
}

Output

When you will compile and execute the above example you will get the output as follows :

Download Source Code