Java Garbage Collection

Java may be the most widely used programming language to rely on garbage collection. The benefits of garbage collection are undeniable as it ensures increased reliability, decoupling of memory management from class interface design, and less developer time spent dealing with memory management errors. The garbage collector in Java is basically a part of the JVM.

The garbage collector in JVM automatically cleans up unused objects. An object is unused if the program holds no more references to it. We can explicitly drop a reference by setting the variable holding the reference to null.

See the coding example below.

TestFinalize.java

//Demonstrating Java Garbage Collection

public class TestFinalize {

protected void finalize() throws Throwable {
System.out.println("finalize() method called");
}

public static void main(String[] args) {
//creation of objects
TestFinalize f1 = new TestFinalize();
TestFinalize f2 = new TestFinalize();

//explicitly dropping references
f1 = null;
f2 = null;

//runs the garbage collector and calls finalize()
System.gc();
}
}

Output:

finalize() method called
finalize() method called

 

Explanation:

The method below runs the garbage collector:

public static void gc()

Calling the gc() method of java.lang.System class suggests that the JVM spend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the JVM has made a best effort to reclaim space from all discarded objects.

The finalize() is a method of the java.lang.Object class that the Garbage Collector (i.e. System.gc() method here) always calls just before the deletion of the object which is eligible for garbage collection, so as to perform clean-up activity. Clean-up activity means resource de-allocation (e.g. closing the resources associated with the objects like files, database connections, network connections etc.).

Since Object class contains the finalize() method hence it is available for every Java class since Object is the superclass of all Java classes. As it is available for every Java class hence garbage collector can call this method on any Java object.

In this program, the finalize() method which is present in the Object class, has an empty implementation, in our class named TestFinalize, clean-up activities are there, so we have to override this method to define our own clean-up activities.