Finalize Java Example
In this post, we feature a comprehensive Finalize Java Example.
This post will acquaint you with one of the important finalize method in java with its detailed explanation, usage and implementation along with example. As the name finalize method in java suggests, it is something used generally at the end to perform certain task. This was just a very generic intoduction in layman terms. Now let us technically discuss the finalize method in detail.
1. Introduction
finalize()
is a method of java.lang.Object
class, which is called by Garbage Collector automatically to perform clean-up actions, just before deleting the object when it is no more referenced. The clean-up actions involve disposal of the allocated system resources, closing the open connections like that with the database, file or network, and similar activities to prevent memory leaks. After the execution of finalize method, garbage collector destructs the object from the memory.
finalize()
method can also be called explicitly with any object in a program. This method can be overridden in any Java class, where programmer can specify the tasks that are to be performed within the method. The main point to note here is that unlike constructors, finalize()
does not have any implicit call to superclass finalize()
method, and the call must be made explicitly within the subclass.
2. Syntax
The syntax of the in-built finalize()
method in the java.lang.Object
class is as follows:
protected void finalize() throws Throwable { }
The access specifier of finalize()
method is protected
. It is not public
, because of encapsulation feature, i.e., because the method should only be invoked by Java Virtual Machine (JVM). On the other hand, it is not private
as finalize()
method can be overriden by the subclass of Object
class, which isn’t allowed in private
access specifier.
finalize()
method does not accept any parameters. Its return type is void
, which means that the method does not return any value.
Throwable
is the exception raised by finalize()
method and throws
keyword specifies that any exception raised will be thrown by the method. The major note to be taken here is that if the garbage collector implicitly calls finalize()
method, then any unchecked exception raised would be ignored by JVM. But if the method is called explicitly by other means, then the exception raised by finalize()
method must be tackled by utilizing exception handling mechanism in the program.
3. Garbage Collection in Java
As the name suggests, Garbage Collection is the process of collecting the unused or unreferenced objects from the heap memory when they are not in use, in order to prevent memory leaks and utilize this memory for other purposes. Unlike C++ where the garbage collection is explicitly performed inside the destructor, Java has no destructor and hence garbage collection task is carried out implicitly by JVM.
Garbage collection is not necessarily carried out as soon as the object is not referenced anymore, whereas JVM generally calls garbage collector in certain time intervals and then it collects all those objects which are no more referenced. Garbage collector calls finalize()
method before destructing the object, so as to perform all the clean-up tasks releavant to the object.
Garbage collector is automatically be invoked by JVM after certain time intervals. But if required, a programmer can explicitly request JVM to call garbage collector via System.gc()
or RunTime.getRunTime().gc()
method within the class, which in turn makes an implicit call to java.lang.Object.finalize()
method. The major point to be considered here is that calling System.gc()
method only requests JVM to invoke garbage collector and does not guarantee that it is invoked immediately. Therefore, it is sometimes not much preferable to make explicit call to this method.
4. Finalize Java Example
In this section we will implement the finalize()
method with the help of an example in Java. The code is written in Nodepad++ and executed via Command Prompt. Java 8 IDE is installed and used for implementation. The code is same and can run on any Java’s IDE like Eclipse, NetBeans, Spring, etc.
FinalizeDemo.java
//Code to demonstrate working of finalize() method. package com.javacodegeeks.finalizedemo; public class FinalizeDemo { //Main method of the function public static void main(String[ ] args) { //Creating an object of the class 'FinalizeDemo' FinalizeDemo fd = new FinalizeDemo(); try { //Explicit call to finalize() method System.out.println("Before calling finalize() explicitly"); fd.finalize(); //Calling Garbage Collector method which implicitly calls finalize() method System.out.println("Before calling Garbage Collector"); System.gc(); System.out.println("Garbage collected"); } catch(Throwable e) { System.out.println("An exception occured"); e.printStackTrace(); } } //Overriding finalize() method. @Override protected void finalize() throws Throwable { System.out.println("Inside finalize() method"); } }
The above program demonstrates the working of finalize()
method when called explicitly with the object, fd
of the class FinalizeDemo
and also implicitly via System.gc()
method. The program overrides the finalize()
method. When an explicit call is made by fd.finalize()
statement, the overriden finalize()
method is executed like a normal user defined Java method and the object is not destroyed, because no call is made to the super class finalize()
method. Later in the program, a request is sent to JVM to invoke garbage collector via System.gc()
statement. Once, the permission is granted by JVM, the garbage collector implicitly invokes the finalize()
method before destroying the object.
Now, the set the appropriate path on the command prompt (cmd) where the program file FinalizeDemo.java is stored. To compile and execute the program write the following commands on cmd:
> javac FinalizeDemo.java > java FinalizeDemo
The following is the output of FinalizeDemo.java program that occurs on the successful execution of the program:
Output
Before calling finalize() explicitly Inside finalize() method Before calling Garbage Collector Inside finalize() method Garbage collected
I hope you liked this article. If so, then smush the like button and please share your valuable reviews in the comment section below.
5. Download the Source Code
This was an example to demonstrate the usage of finalize() method via Java Program.
You can download the full source code of this example here: Finalize Java Example
Excellent example. Clicked dislike by mistake.
Good Explanation with example of the topic Java Finalize topic.