×

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 Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Bully Algorithm code in Java

Election algorithms include the bully algorithm, mainly used to select a coordinate. To find a coordinator in a distributed system that can carry out the tasks required by other processes,...

4 minutes read.

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.