Garbage Collection in Java

Garbage Collection means and as the name implies freeing up of space by the waste objects or garbage to avoid memory leaks. Since objects are dynamically allocated by using the new keyword how these objects are destroyed and their memory is released for reallocation.

Some languages like in C and C++ dynamically allocated memory must be manually released by the use of delete operator so that there are no memory leaks in our program.

The approach that Java takes, is that it handles the deallocation of memory automatically for you so you don’t have to deallocate memory every time you allocate it,

This technique is called automatic garbage collectionIt works as when no references to an object exist, it is assumed to be no longer needed and memory occupied by the object can be released to the free pool of memory so that is can e reclaimed.

There is no explicit need to destroy objects as in C++.

Different Java runtime implementations take a varying approach to garbage collection.

finalize()  method:

finalize()  method is a method that is used when an object is needed to perform an action when it is destroyed.

Example: When an object is holding a non-Java resource such as a file, then we should make sure these resources are freed before the object is destroyed and to handle such situations Java provides a mechanism called finalzation .

Using this mechanism we can add specific actions that will occur when an object is just about to be destroyed.

How to use finalize() method: 

Syntax : 
protected void finalize() throws Throwable
{
// finalization code
}

We simply define finalize() method, whenever the Java runtime is about to recycle an object it calls the finalize() method of that class, and inside the finalize()  we define those actions that are to be performed before the object gets destroyed.

The garbage collector runs periodically checking for the objects that are no longer referenced by any running state or indirectly through other objects.

Here, the keyword protected  is an access specifier that prevents access to the finalize() method by any code defined outside the class.

Example:

public class example {
public static void main(String[] args)

{
example obj = new example();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector  
System.gc();
System.out.println("garbage collected ");
}
protected void finalize()
{
System.out.println("finalize method is called");
}

Output: 

925858445

garbage collected

finalize method is called

Note:

C and C++ allow us to define a destructor for a  class which is called when an object goes out of scope. Java does not provide destructor rather it provides us with finalize() that approximates the function of a destructor. While the use of finalize() is minimal because of Java’s garbage collection subsystem.