×

Java finalize()

Java finalize()

In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the deletion or destroying the object (which is eligible for garbage collection). It is called by the garbage collector when there are no more references to object. It removes the unused objects in order to free up theheap memory. In short, we can say thatit is used to perform cleanup activity.

Syntax:

 protected void finalize() throws Throwable
{
} 

How garbage collector uses finalize() method?

The garbage collector calls finalize() method, when an object is dereferenced. The dereferenced object need to be destroyed by the garbage collector.

Consider the example, a class named Employee is declared having an object named emp.

 public class Employee
{
          //statements
          Employee emp = new Employee();
          emp = null;
} 

The object emp is first declared and has a reference to the Employee class.In the next statement, we have assigned null value to the object emp. It means no reference at all. So,the garbage collector marks it as garbage.Now, the garbage collector invokes thefinalize() method to destroy the object.

Overriding finalize() Method

The following code snippet shows how to override the finalize method in a class named Sample.

Samle.java

 public class Sample
{
//overriding finalize() method
    @Override
    protected void finalize() throws Throwable
    {
        try
        {
System.out.println("Inside the finalize method");
        }
catch(Throwable e)
        {
throw e;
        }
        finally
        {
          //invokes the finalize() method of the Object class
super.finalize();
        }
    }
//driver code
public static void main(String a[]) throws Throwable
    {
        Sample s = new Sample();
          //invokes the Sample class finalize method
s.finalize();
    }
} 

Output:

Inside the finalize method

We can also call the finalize() method explicitly. Let’s understand it through a Java program.

Callingfinalize() method Explicitly

When finalize() method is called explicitly, the JVM executes it as normal method. The JVM will not be able to remove or destroy the object from memory. The explicit method call can only work with garbage collector to release memory.

Sample.java

 public class Sample
{
    public static void main(String a[])
    {
        Sample s1 = new Sample();
        Sample s2 = new Sample();
        s2 = null;
        // Explicit call
        s1.finalize();
System.out.println("Garbage collector");
System.gc(); //Implicit call to finilize() method     
    }
    @Override
    protected void finalize()
    {
System.out.println("finilize() method called");
    }
} 

Output:

 finilize() method called
Garbage collector
finilize() method called 

In the above code snippet, no object is destroyed when finalize() method is called. But when the gc() method of the System class is invoked, it makes an implicit call to the finalize() method and removes the s2 object from memory.

Drawbacks of Usingfinalize()Method

  1. During the program execution there is no specific time allocated for garbage collection. It can execute at any time evenin between of the program execution. It also affects the performance ofthe system and system might run out of resources, as it has limited resources.
  2. As the garbage collection is based on JVM, a program may run without any errors on one system but might face problems on another.
  3. An exception thrown by the finalize() method is not handled by garbage collector. Additionally, it will also be not logged in the log files.
  4. There is a possibility that it may delete live objects that are being used further inside the same program.

Alternativeoffinalize() Method

Considering the drawbacks offinalize() method, the following alternative can be used instead of using finalize() method.

Using Cleaner class

We can use the Java Cleaner class to perform the functionality of dereference of an object. Java Cleaner class is presented since Java 9. It belongs to java.lang.ref.When an object is dereferenced, an alert is sent to the Cleaner class object. The object is then registered with the Cleaner class object using the register() method.

CleanerSample.java

 import java.lang.ref.Cleaner;
public class CleanerSample
{
          public static void main(String a[])
          {
                   System.out.println("Start CleanerSample...");
                   Cleaner cleaner = Cleaner.create();
                   CleanerSample obj = new CleanerSample();
                   //register cleaner
                   cleaner.register(obj, new CleanerSampleRunnable());
                   for (int i = 1; i<= 100000; i++)
                   {
                             String[] s1 = new String[1000];
                             try
                             {
                                      Thread.sleep(1);
                             } catch (InterruptedException e)
                             {
                                      e.printStackTrace();
                             }
                   }
                   System.out.println("Execution Finished...");
          }
          private static class CleanerSampleRunnable implements Runnable
          {
                   public void run()
                   {
                             System.out.println("CleanerSample cleaning action executed...");
                   }
          }
} 

In the above code, the object objis registered with the Cleaner class. So, the runnable instance CleanerSampleRunnable gets executed after the object CleanerSampleRunnableis destroyed.

Output:

 Start CleanerSample...
CleanerSample cleaning action executed...
Execution Finished... 

In this way, we have understood the concept of finalize() method in Java, its drawbacks and where and when to use finalize() method with the help of Java programs.


Related Topics

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Primitive Data Types

Primitive data types are the simplest data types in a programming language. They’re predefined in the language. The names of the primitive types are quite descriptive of the values that...

2 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.