Destructor in Java

Hiten Kanwar Oct 12, 2023
Destructor in Java

The destructor is the opposite of a constructor. On the one hand, where a constructor is used to initialize an object, a destructor is used to destroy (delete) an object which releases the resource occupied by the object.

This tutorial will discuss destructors in Java, their working, and their methods.

Java does not have destructors neither it has a direct equivalent to it. Nevertheless, it is a potent language, and one reason for that is the garbage collector. Java provides us with a garbage collector who works similar to a destructor. The garbage collector, a program(Thread) that runs on Java Virtual Machine (JVM), automatically free up the memory by deleting the unused objects.

In Java, allocation and deallocation of memory are efficiently handled by this garbage collector. When the life cycle of an object is completed, the garbage collector shows up, deletes that object, and deallocates or releases the memory occupied by that object. This method is also known as finalizers which are non-deterministic. But the issue is that invocation of this method (finalizers) is not guaranteed as it invokes implicitly.

Working of Destructors and the finalize() Method in Java

When an object is created in Java, it occupies memory in the heap. Threads further use these objects, and if a thread does not use the object, they become eligible for garbage collection by the garbage collector. Thus, the memory occupied by these objects now becomes vacant and can be further utilized by any new entity. When the garbage collector destroys any object, the Java Runtime Environment (JRE) calls the finalize() method to close the connections, such as network and database connections.

We cannot force the garbage collector to execute and destroy the object. But Java here provides an alternative method. The java object provides us with finalize() method, which works similarly to a destructor. However, it can be called only once.

The point to understand is the finalize() method is not a destructor but provides extra security and further ensures external resources like closing the file before shutting the operation (program) and works quite similar to the destructor.

See the code below.

public class Dest_java {
  public static void main(String[] args) {
    Dest_java des = new Dest_java();
    des.finalize();
    des = null;
    System.gc();
    System.out.print("main() method ");
  }
  protected void finalize() {
    System.out.print("Destroyed ");
  }
}

Output:

Destroyed main() method Destroyed