×

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

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Web Service Response Time Calculation in Java

Administration response time or reaction time is the typical measure of time it takes for a solicitation to be handled by a PC framework, like your organization switch. In the...

4 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 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 Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.