×

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 Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Round Robin Scheduling Program in Java

A CPU scheduling technique is known as Round Robin (RR). Additionally, network schedulers employ it. It was created specifically for a time-sharing system. The temporal slicing scheduling algorithm is another...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Bean class in Java

The web applications that are created with the help of the JSP or Java Server Pages generally have fairly more functionality than the web pages that specifically are created with...

5 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java 13 New Features

The Java SE Platform's JDK 13 version is an open-source reference implementation defined by the Java Community's JSR 388 Process. The necessary modifications made in Java 13 are listed below....

6 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 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 Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Find the Frequency of Each Element in the Array in Java

We may count the occurrence of each element in the array of items. Maintaining one array to store the counts of each array element is one strategy for solving this issue....

3 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.